将字符串,整数和数组的JSON对象解组为映射

时间:2015-08-09 14:00:18

标签: 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: interface conversion: interface is []interface {}, not []string

1 个答案:

答案 0 :(得分:2)

这是转换无法实现的,因为slice of struct != slice of interface it implements! 要么你可以逐个获取元素并将它们放入[]string这样的内容:http://play.golang.org/p/1yqScF9yVX

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