arrays - 将字符串、整数和数组的 JSON 对象解码到映射中

标签 arrays json dictionary go

我喜欢使用 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 :

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

最佳答案

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

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

关于arrays - 将字符串、整数和数组的 JSON 对象解码到映射中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31905043/

相关文章:

c# - Entity Framework : many to many relationship tables

python - 检查键是否在字典中并在同一个 "if"中获取它的值是否安全?

java - 打印 Java 数组的最简单方法是什么?

c - 如何检查输入何时超出二维数组列中的行?

python - 有效地将扁平字符串解析为嵌套字典

c++ - 如何在 map 中使用 tolower 和 lambda 函数? C++

python - 遍历字典

php - 将数组插入mysql表

javascript - 对链接数组进行排序

javascript - 将 JSON 对象转换为响应对象