【问题标题】:How do you unmarshal a JSON object to a Golang struct when the JSON field key is a date?当 JSON 字段键是日期时,如何将 JSON 对象解组为 Golang 结构?
【发布时间】:2021-09-21 23:39:49
【问题描述】:

我有以下 JSON 响应。将其解组为 Golang 结构的最佳方法是什么? JSON to Golang 自动生成的结构是说结构的命名属性应该是 20210712、20210711、20210710 等,但这不起作用,因为随着未来日期的变化,结构字段会有所不同。动态执行此操作的最佳方法是什么?

{
  "data": {
    "2021-07-12": {
      "Neutral": 3,
      "Positive": 4,
      "Negative": 4
    },
    "2021-07-11": {
      "Neutral": 0,
      "Positive": 1,
      "Negative": 4
    },
    "2021-07-10": {
      "Neutral": 0,
      "Positive": 0,
      "Negative": 3
    }
  }
}

【问题讨论】:

    标签: json go struct marshalling unmarshalling


    【解决方案1】:

    根据 Burak Serdar 的输入,我为您的场景创建了一个简单的程序,如下所示:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Item struct {
        Neutral  int
        Positive int
        Negative int
    }
    
    type Data struct {
        Data map[string]Item `json:"data"`
    }
    
    func main() {
    
        var resData Data
    
        var data = []byte(`{
       "data":{
          "2021-07-12":{
             "Neutral":3,
             "Positive":4,
             "Negative":4
          },
          "2021-07-11":{
             "Neutral":0,
             "Positive":1,
             "Negative":4
          },
          "2021-07-10":{
             "Neutral":0,
             "Positive":0,
             "Negative":3
          }
       }
    }`)
    
        if err := json.Unmarshal(data, &resData); err != nil {
            panic(err)
        }
        fmt.Println(resData)
        fmt.Println(resData.Data["2021-07-10"])
    
    }
    

    输出:

    {map[2021-07-10:{0 0 3} 2021-07-11:{0 1 4} 2021-07-12:{3 4 4}]}
    {0 0 3}
    

    【讨论】:

      【解决方案2】:

      您可以使用地图:

      type Item struct {
         Neutral int
         Positive int
         Negative int
      }
      
      type Data struct {
        Data map[string]Item `json:"data"`
      }
      

      解组时,可以使用data.Data["2021-07-11"]

      【讨论】:

        猜你喜欢
        • 2020-12-27
        • 1970-01-01
        • 2019-03-28
        • 2020-10-14
        • 1970-01-01
        • 1970-01-01
        • 2018-01-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多