简体   繁体   English

如何解组嵌套结构 JSON

[英]How to unmarshal nested struct JSON

I'm studying about JSON encoding and decoding, but I'm stuck on nested struct unmarshaling.我正在研究 JSON 编码和解码,但我坚持嵌套结构解组。

I tried to declare both the children struct as external type and explicit struct in the parent as follow:我试图将子结构声明为外部类型和父结构中的显式结构,如下所示:

type WorkingSession struct {
    Project Project `json:"project"`
    Hours int    `json:"hours"`
    Date  string `json:"date"`
    Nested struct{
        NestedField string `json:"nested_field"`
    } `json:"nested"`
}

type Project struct {
    Name string `json:"name"`
}

But when I execute my main:但是当我执行我的主要内容时:

func main() {
    document:= []byte(`
        {
            "project " : {"name" : "Project 1"},
            "hours" : 4,
            "date" : "2019-11-03",
            "nested" : {"nested_field" : "test"}
        }
    `)

    var ws WorkingSession

    err := json.Unmarshal(document, &ws)

    log.Println(ws)
    if err != nil {
        log.Fatal(err.Error())
    }

}

It does not print the project nested fields:它不打印project嵌套字段:

2019/11/03 11:24:04 {{} 4 2019-11-03 {test}}

What is wrong?怎么了?

You have another typo in your project key.您的project密钥中有另一个错字。

You have a space in "project " .您在"project "中有一个空间。 Remove the space and it will work fine.删除空间,它将正常工作。

document:= []byte(`
    {
        "project" : {"name" : "Project 1"},
        "hours" : 4,
        "date" : "2019-11-03",
        "nested" : {"nested_field" : "test"}
    }
`)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM