登录
首页 >  Golang >  Go问答

根据密钥解组 JSON

来源:stackoverflow

时间:2024-04-24 16:45:36 170浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《根据密钥解组 JSON》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我从网络接收 json 格式的数据,我需要根据密钥对其进行解组。

这是数据示例:

{
  "foo": {
    "11883920": {
      "fieldA": 123,
      "fieldB": [
        {
          "fieldC": "a",
          "fieldD": 1173653.22
        }
      ]
    }
  },
  "bar": {
     "123": {
       "fieldE": 123
     }
   }
  "anyOtherkey": {...}
}

逻辑是,如果密钥是 foo,则应将其解组为 foostruct,如果 bar - 则应解组为 barstruct。 实现这个逻辑的最佳方法是什么? (我不想将其解组到 map[string]interface{},也许可以使用 json.newdecoder() 函数,但我无法获得预期结果)。


解决方案


只需创建一个包含两个字段的类型:

type mytype struct {
    foo      *foostruct `json:"foo,omitempty"`
    bar      *barstruct `json:"bar,omitempty"`
    otherkey string     `json:"other_key"`
}

将 json 解组为该类型,然后只需检查 ig foo 和/或 bar 是否为 nil 即可了解您正在使用的数据。

这是一个演示 Demo,展示它的样子

其本质是:

type foo struct {
    field int `json:"field1"`
}

type bar struct {
    message string `json:"field2"`
}

type payload struct {
    foo   *foo   `json:"foo,omitempty"`
    bar   *bar   `json:"bar,omitempty"`
    other string `json:"another_field"`
}

foobar 字段是指针类型,因为值字段会使确定实际设置的字段变得更加麻烦。 omitempty 位允许您封送相同类型以重新创建原始有效负载,因为 nil 值不会显示在输出中。

要检查原始 json 字符串中设置了哪个字段,只需编写:

var data Payload
if err := json.Unmarshal([]byte(jsonString), &data); err != nil {
    // handle error
}
if data.Foo == nil && data.Bar == nil {
    // this is probably an error-case you need to handle
}
if data.Foo == nil {
    fmt.Println("Bar was set")
} else {
    fmt.Println("Foo was set")
}

仅此而已

到这里,我们也就讲完了《根据密钥解组 JSON》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>