登录
首页 >  Golang >  Go问答

将 JSON 解组为 Struct

来源:stackoverflow

时间:2024-04-23 16:09:33 201浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《将 JSON 解组为 Struct》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我正在尝试将以下 json 字符串解组到下面的结构中;

{
   "io.confluent.connect.avro.connectdefault":{
      "lastmodifiedat":{
         "string":"2022-09-01t02:22:19+00:00"
      },
      "taxrateid":{
         "int":5
      },
      "basedon":{
         "string":"markup"
      },
      "pricetax":{
         "double":2.04
      },
      "price":{
         "int":24
      },
      "status":{
         "string":"active"
      },
      "costprice":{
         "int":24
      },
      "createdat":{
         "string":"2022-09-01t02:22:19+00:00"
      },
      "productid":{
         "int":3545
      },
      "ownershipid":{
         "int":1
      },
      "dbid":{
         "int":3655
      },
      "markuppercentage":{
         "int":0
      }
   }
}
type Wrapper struct {
    Message `json:"io.confluent.connect.avro.ConnectDefault"`
}

type Message struct {
    DbId Field `json:"dbId"`
}

type Field struct {
    Value map[string]interface{}
}

但它为我提供了 field 地图的空值。不确定我在这里做错了什么。


正确答案


这是因为你有额外的嵌套级别:

type Message struct {
    DbId map[string]interface{} `json:"dbId"`
}

dbid 属性的值是 mapstring 的任意值。

今天关于《将 JSON 解组为 Struct》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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