2015-08-09 87 views
1

我喜欢解组使用解码()JSON字符串:解组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 

回答

2

这是不可能的转换,因为slice of struct != slice of interface it implements
要么你可以得到一个要素之一,并把它们放在一个[]string这样的:

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

+0

我选择第二。我将map [string] interface {}类型更改为struct {Id int Command String Names [] string},然后像以前一样使用Decode()。工作正常。 – Michael