2015-08-09 85 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