使用接口与 Golang 映射和结构以及 JSON

Using Interfaces with Golang Maps and Structs and JSON

我有一些 JSON 代码看起来像:

{
    "message_id": "12345",
    "status_type": "ERROR",
    "status": {
        "x-value": "foo1234",
        "y-value": "bar4321"
    }
}

或者可以像这样。如您所见,"status" 元素从标准字符串对象变为基于 status_type 的字符串数组对象。

{
    "message_id": "12345",
    "status_type": "VALID",
    "status": {
        "site-value": [
            "site1",
            "site2"
        ]
    }
}

我在想我需要让 "Status" 的结构采用像 "map[string]interface{}" 这样的映射,但我不确定具体该怎么做。

你也可以在 playground 上看到这里的代码。
http://play.golang.org/p/wKowJu_lng

package main

import (
    "encoding/json"
    "fmt"
)

type StatusType struct {
    Id     string            `json:"message_id,omitempty"`
    Status map[string]string `json:"status,omitempty"`
}

func main() {
    var s StatusType
    s.Id = "12345"
    m := make(map[string]string)
    s.Status = m
    s.Status["x-value"] = "foo1234"
    s.Status["y-value"] = "bar4321"

    var data []byte
    data, _ = json.MarshalIndent(s, "", "    ")

    fmt.Println(string(data))
}

我想通了,我想..

package main

import (
    "encoding/json"
    "fmt"
)

type StatusType struct {
    Id     string            `json:"message_id,omitempty"`
    Status map[string]interface{} `json:"status,omitempty"`
}

func main() {
    var s StatusType
    s.Id = "12345"
    m := make(map[string]interface{})
    s.Status = m

    // Now this works
    // s.Status["x-value"] = "foo1234"
    // s.Status["y-value"] = "bar4321"

    // And this works
    sites := []string{"a", "b", "c", "d"}
    s.Status["site-value"] = sites

    var data []byte
    data, _ = json.MarshalIndent(s, "", "    ")

    fmt.Println(string(data))
}