繁体   English   中英

如何为json创建正确的结构

[英]How to create correct struct for json

如何正确解析 json 我有以下 json 文件

{
    "hello": {
        "title": "Golang",
        "story": [
            "Go lang story",
            "Channel story"
        ],
        "options": [
            {
                "text": "That story",
                "arc": "west"
            },
            {
                "text": "Gee",
                "arc": "east"
            }
        ]
    },
    "world": {
        "title": "Visiting",
        "story": [
            "Boo",
            "Doo",
            "Moo",
            "Qoo"
        ],
        "options": [
            {
                "text": "weird",
                "arc": "west"
            },
            {
                "text": "funny",
                "arc": "north"
            }
        ]
    }
}

我已经为内部创建了这些结构

type chapter struct{
    Title string `json:"title"`
    Story []string `json:"story"`
    Option []option `json:"options"`
}

type option struct {
    Text string `json:"text"`
    Arc string `json:"arc"`
}

但我不知道如何解析像“hello”和“world”这样的包装器

您需要做的就是构建根映射。

{
    "hello":{},
    "world":{}
}

这里的helloworld也在地图中。 所以你也需要构造它们。

 var root map[string]chapter
 json.Unmarshal(JSONDATA,&root)

游乐场示例: https : //play.golang.org/p/VZ9Bn215dDW

暂无
暂无

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

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