登录
首页 >  Golang >  Go问答

将 json 数组解析为 struct golang 列表

来源:stackoverflow

时间:2024-04-18 08:36:34 184浏览 收藏

你在学习Golang相关的知识吗?本文《将 json 数组解析为 struct golang 列表》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我有一个如下所示的 json,我正在尝试为下面的 json 创建一个结构,当我解组它时,它可以为我存储数据。

{
  "clientmetrics": [
    {
      "clientid": 951231,
      "customerdata": {
        "process": [
          "abc"
        ],
        "mat": [
          "kkk"
        ]
      },
      "legcustomer": [
        8773
      ]
    },
    {
      "clientid": 1234,
      "legcustomer": [
        8789
      ]
    },
    {
      "clientid": 3435,
      "otherids": [
        4,
        32,
        19
      ],
      "legcustomer": [
        10005
      ]
    },
    {
      "clientid": 9981,
      "catid": 8,
      "legcustomer": [
        13769
      ]
    },
    {
      "clientid": 12124,
      "otherids": [
        33,
        29
      ],
      "legcustomer": [
        12815
      ]
    },
    {
      "clientid": 8712,
      "customerdata": {
        "process": [
          "college"
        ]
      },
      "legcustomer": [
        951
      ]
    },
    {
      "clientid": 23214,
      "legcustomer": [
        12724,
        12727
      ]
    },
    {
      "clientid": 119812,
      "catid": 8,
      "legcustomer": [
        14519
      ]
    },
    {
      "clientid": 22315,
      "otherids": [
        32
      ],
      "legcustomer": [
        12725,
        13993
      ]
    },
    {
      "clientid": 765121,
      "catid": 8,
      "legcustomer": [
        14523
      ]
    }
  ]
}

clientmetrics 是一个 json 数组,其中包含每个 clientmetric 对象。每个 clientmetric 对象都可以包含各种字段。我尝试了类似下面的方法,但我对如何添加休息感到困惑,因为我来自 java 背景,而且我没有看到 golang 中有可用的设置。也对如何添加 customerdata 对象感到困惑。

type ClientMetrics struct {
    ClientId    int64
    CatId       int64

  

}

将 json 上方的 unmarshall 转换为 golang 中的 clientmetrics 结构列表的最佳方法是什么?


正确答案


您可以在此处使用 json 访问 https://mholt.github.io/json-to-go/

但它会重复 customerdata 结构两次,确保您应该删除其中之一。

我为您的场景创建了一个示例结构,如下所示:

type AutoGenerated struct {
        ClientMetrics []struct {
            ClientID     int `json:"clientId"`
            CustomerData struct {
                Process []string `json:"Process"`
                Mat     []string `json:"Mat"`
            } `json:"customerData,omitempty"`
            LegCustomer []int `json:"legCustomer"`
            OtherIds    []int `json:"otherIds,omitempty"`
            CatID       int   `json:"catId,omitempty"`
        } `json:"clientMetrics"`
    }

您可以在 go 演示中运行它:https://go.dev/play/p/R1M1HfzpEny

如果您使用 vs code,有一些扩展可以完成这项工作。 其中之一名为 Paste JSON as Code

  1. 安装扩展
  2. 将 json 复制到剪贴板中 (ctrl+c)
  3. 按 ctrl+shift+p 并选择 将 json 粘贴为代码
  4. 输入结构体名称并按 enter

如果这对您不起作用,您可以随时使用此站点 https://mholt.github.io/json-to-go/,但更好的做法是使用取消选择 inline typedefinitions 选项后获得的结构。

本篇关于《将 json 数组解析为 struct golang 列表》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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