英文:
Unmarshal JSON object of strings, ints and arrays into a map
问题
我喜欢使用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
英文:
I like to unmarshal a JSON string using Decode():
var message Message
decoder := json.NewDecoder(s)
err = decoder.Decode(&message)
My data structure is
type Message map[string]interface{}
The test data is as follows:
{
"names": [
"HINDERNIS",
"TROCKNET",
"UMGEBENDEN"
],
"id":1189,
"command":"checkNames"
}
It's working fine for numbers and strings, but with the string array I get following panic:
panic: interface conversion: interface is []interface {}, not []string
答案1
得分: 2
这是因为无法通过转换实现,因为一个结构体切片与它实现的接口切片不相等。你可以逐个获取元素并将它们放入[]string
中,像这样:http://play.golang.org/p/1yqScF9yVX
或者更好的方法是,使用json包的功能来解包你的模型格式数据:http://golang.org/pkg/encoding/json/#example_Unmarshal
英文:
this is not possible by conversion because a slice of struct != slice of interface it implements!
either you can get the elements one by one and put them into a []string
like this: http://play.golang.org/p/1yqScF9yVX
or better, use the capabilities of the json package to unpack the data in your model format : http://golang.org/pkg/encoding/json/#example_Unmarshal
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论