我有一个类似于这个的 JSON 对象:
{
"name": "Cain",
"parents": {
"mother" : "Eve",
"father" : "Adam"
}
}
现在我想将“name”和“mother”解析到这个结构中:
struct {
Name String
Mother String `json:"???"`
}
我想用 json:...
结构标签指定 JSON 字段名称,但是我不知道该用什么作为标签,因为它不是我感兴趣的顶级对象在。我在 encoding/json
中没有发现任何相关信息包文档或流行的博客文章 JSON and Go .我还测试了 mother
、parents/mother
和 parents.mother
。
最佳答案
只要传入的数据不太动态,就可以使用结构。
http://play.golang.org/p/bUZ8l6WgvL
package main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string
Parents struct {
Mother string
Father string
}
}
func main() {
encoded := `{
"name": "Cain",
"parents": {
"mother": "Eve",
"father": "Adam"
}
}`
// Decode the json object
u := &User{}
err := json.Unmarshal([]byte(encoded), &u)
if err != nil {
panic(err)
}
// Print out mother and father
fmt.Printf("Mother: %s\n", u.Parents.Mother)
fmt.Printf("Father: %s\n", u.Parents.Father)
}
https://stackoverflow.com/questions/13593519/