使用与Golang Maps和Structs以及JSON的接口

时间:2015-04-02 02:18:14

标签: json dictionary interface go

我有一些看起来像的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"
        ]
    }
}

我在想我需要让我的“状态”结构采用像“map [string] interface {}”这样的地图,但我不确定该怎么做。

你也可以在操场上看到这里的代码 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))
}

1 个答案:

答案 0 :(得分:5)

我想出来了,我想..

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))
}