生成及解析json
func Jsons() {
var err error
// json to struct
type List struct {
Id int `json:"id"`
Name string `json:"name"`
Mobile string `json:"mobile"`
IsDelete bool `json:"is_delete"`
}
type Data struct {
Code int `json:"code"`
List []List `json:"list"`
}
jsonStr := `{"code": 1, "list": [
{"id": 1, "name": "刘备", "mobile": "13399999999", "is_delete": true},
{"id": 2, "name": "张飞", "mobile": "13388888888", "is_delete": false},
{"id": 3, "name": "关羽", "mobile": "13366666666", "is_delete": true}
]}`
fmt.Println("--------------------------------------- json to struct")
var data Data
err = json.Unmarshal([]byte(jsonStr), &data)
if err == nil {
fmt.Println(data)
} else {
fmt.Println(err.Error())
}
fmt.Println("--------------------------------------- json to map")
// json to map
mapData := make(map[string]interface{})
err = json.Unmarshal([]byte(jsonStr), &mapData)
if err == nil {
fmt.Println(mapData)
} else {
fmt.Println(err.Error())
}
fmt.Println("--------------------------------------- struct to json")
// struct to json
structJson, err := json.Marshal(data)
if err == nil {
fmt.Println(string(structJson))
} else {
fmt.Println(err.Error())
}
fmt.Println("--------------------------------------- map to json")
// map to json
mapJson, err := json.Marshal(mapData)
if err == nil {
fmt.Println(string(mapJson))
} else {
fmt.Println(err.Error())
}
}
Debug输出
image.png
网友评论