【问题标题】:Using Interfaces with Golang Maps and Structs and JSON使用带有 Golang 映射和结构以及 JSON 的接口
【发布时间】:2015-06-06 21:03:34
【问题描述】:

我有一些 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))
}

【问题讨论】:

    标签: json dictionary interface go


    【解决方案1】:

    我想通了,我想..

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

    【讨论】:

    • 您可以尝试使用 RawMessage 类型延迟解组状态。然后,根据 status_type 值对其进行 Unmarshal。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    相关资源
    最近更新 更多