变量JSON结构与Go结构类型的映射

huangapple go评论70阅读模式
英文:

Variable JSON structure mapping with Go struct type

问题

我有一个如下的JSON:

{
  "Key1": "Value1",
  "Key2": "Value2",
  "Key3": {
    "InnerKey1": "InnerValue1",
    "InnerKey2": "InnerValue2",
    ...
  }
}

我遇到的问题是Key3的结构包含一个长度可变的键值对。可能客户端会发送给我另一个键。在Go语言中,我该如何创建一个适应这种情况的struct结构?

英文:

I have a JSON that is as follows

{
  "Key1": "Value1",
  "Key2": "Value2",
  "Key3": {
    "InnerKey1": "InnerValue1",
    "InnerKey2": "InnerValue2",
    ...
  }
}

The problem I have is with the Key3 structure which contains a key value of variable length. It is possible that the client sends me another key. How do I create a struct for this in Go

答案1

得分: 1

你可以使用 json2go。对于变量部分,你可以使用一个 map。

然后你会得到:

type AutoGenerated struct {
    Key1 string `json:"Key1"`
    Key2 string `json:"Key2"`
    Key3 map[string]string `json:"Key3"`
}
英文:

You can use json2go. For the variable part you could use a map

And you get:

type AutoGenerated struct {
	Key1 string `json:"Key1"`
	Key2 string `json:"Key2"`
	Key3 map[string]string `json:"Key3"`
}

huangapple
  • 本文由 发表于 2017年2月16日 00:00:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/42254256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定