这个简洁的JSON文档的Go结构是什么?

时间:2017-06-08 21:28:13

标签: json go

文档具有最小的键/值对元数据。在人员列表中,我们可以使用"name":"joe",或者我们可以拥有joe的密钥。错误的关键是错误。

也许这个文档对于Go结构来说太过动态了?我也尝试过YAML,这就是结果问题。结构保持为空,因为它没有正确映射。

游乐场链接:https://play.golang.org/p/PGSjoKvNja

或者我是否需要滚动自己的UnmarshalJSON并为"动作"?提供条件(或切换)?如果是这样的话,那很好。我可以在那里进行强制和验证,遍历文档并检测有问题的泛型操作位是什么,然后创建一个正确类型的结构。

2 个答案:

答案 0 :(得分:1)

如果数据一致,正如@Adrian所说,你不应该去看我所展示的内容。

否则,您应该能够使用json-to-go生成的以下结构来解组您的字符串,这是一个非常有用的工具,可以从json中获取结构

type Custom struct {
    Ball []struct {
        Throw struct {
            Strength string `json:"strength"`
        } `json:"throw"`
    } `json:"ball"`
    Frisbee []struct {
        Fling struct {
            Curve string `json:"curve"`
        } `json:"fling"`
        Catch struct {
            Trick string `json:"trick"`
            Jump string `json:"jump"`
        } `json:"catch"`
    } `json:"frisbee"`
}

然后

func main() {

    var c Custom
    err := json.Unmarshal([]byte(input), &c )
    if err != nil {
        panic(err)
    }

     fmt.Println(input)

}

打印出来

{
    "ball": [{
        "throw": {
            "strength": "60%"
        }
    }, {
        "throw": {
            "strength": "20%"
        }
    }],
    "frisbee": [{
        "fling": {
            "curve": "left"
        }
    }, {
        "catch": {
            "trick": "behind back",
            "jump": "sure"
        }
    }]
}

看看我设置的this Playground

答案 1 :(得分:1)

这将是:

type AutoGenerated struct {
    Ball []struct {
        Throw struct {
            Strength string `json:"strength"`
        } `json:"throw"`
    } `json:"ball"`
    Frisbee []struct {
        Fling struct {
            Curve string `json:"curve"`
        } `json:"fling,omitempty"`
        Catch struct {
            Trick string `json:"trick"`
            Jump string `json:"jump"`
        } `json:"catch,omitempty"`
    } `json:"frisbee"`
}

当然,您可以为每个内联结构定义定义一个单独的类型。您可以使用this在线工具(用于生成上述数据结构)。

相关问题