将包含字符串、整数和数组的JSON对象解析为映射。

huangapple go评论95阅读模式
英文:

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

huangapple
  • 本文由 发表于 2015年8月9日 22:00:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/31905043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定