【问题标题】:Unmarshal JSON object of strings, ints and arrays into a map将字符串、整数和数组的 JSON 对象解组到映射中
【发布时间】:2015-08-09 14:00:17
【问题描述】:

我喜欢使用 Decode() 解组 JSON 字符串:

var message Message
decoder := json.NewDecoder(s)
err = decoder.Decode(&message)

我的数据结构是

type Message map[string]interface{}

测试数据如下:

{
  "names": [
    "HINDERNIS",
    "TROCKNET",
    "UMGEBENDEN"
  ], 
  "id":1189,
  "command":"checkNames"
}

它对数字和字符串工作正常,但使用字符串数组时我会出现以下恐慌:

panic: interface conversion: interface is []interface {}, not []string

【问题讨论】:

    标签: arrays json dictionary go


    【解决方案1】:

    这无法通过转换实现,因为 slice of struct != slice of interface it implements!
    或者你可以一个一个地获取元素并将它们放入[]string,如下所示:http://play.golang.org/p/1yqScF9yVX

    或者更好的是,使用 json 包的功能来解压模型格式的数据:http://golang.org/pkg/encoding/json/#example_Unmarshal

    【讨论】:

    • 我选择了第二个。我将 map[string]interface{} 类型更改为 struct {Id int Command string Names []string },然后像以前一样使用 Decode()。工作正常。
    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多