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