我有一个json文件,如下所示:
{
"Key1": "value1",
"Key2": [
"value2",
"value3",
],
}
我试图使用下面的结构来反序列化json,然而,反序列化后,只有key2有值,key1为空。
问题:反序列化json的正确结构是什么?
data := map[string][]string{}
_ = json.Unmarshal([]byte(file), &data)
使用struct
type Test struct {
Key1 string
Key2 []string
}
func main() {
testJson := `{"Key1": "value1","Key2": ["value2","value3"]}`
var test Test
json.Unmarshal([]byte(testJson), &test)
fmt.Printf("%s, %s", test.Key1 , test.Key2 )
}
演示使用map
创建到空接口的字符串映射:
var result map[string]interface{}
testJson := `{"Key1": "value1","Key2": ["value2","value3"]}`
var result map[string]interface{}
json.Unmarshal([]byte(testJson ), &result)
演示您可以将Json解码为map[string]interface{}
,或struct
建模数据,甚至只是一个空的interface{}
我通常使用struct
,因为它避免了我做类型断言的任何需要(解码器处理这些东西)。
最后,如果由于某种原因不能立即解码成结构体,我发现这个库非常有用:https://github.com/mitchellh/mapstructure
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type Data struct {
Key1 string
Key2 []string
}
func main() {
var data = `{
"Key1": "value1",
"Key2": [
"value2",
"value3"
]
}`
mapdata := make(map[string]interface{})
var inter interface{}
obj := Data{}
if err := json.
NewDecoder(bytes.NewBufferString(data)).
Decode(&mapdata); err != nil {
panic(err)
} else {
fmt.Printf("Decoded to map: %#vn", mapdata)
}
if err := json.
NewDecoder(bytes.NewBufferString(data)).
Decode(&inter); err != nil {
panic(err)
} else {
fmt.Printf("Decoded to interface: %#vn", inter)
}
if err := json.
NewDecoder(bytes.NewBufferString(data)).
Decode(&obj); err != nil {
panic(err)
} else {
fmt.Printf("Decoded to struct: %#vn", obj)
}
}
Decoded to map: map[string]interface {}{"Key1":"value1", "Key2":[]interface {}{"value2", "value3"}}
Decoded to interface: map[string]interface {}{"Key1":"value1", "Key2":[]interface {}{"value2", "value3"}}
Decoded to struct: main.Data{Key1:"value1", Key2:[]string{"value2", "value3"}}
https://play.golang.org/p/K31dAVtWJNU