登录
首页 >  Golang >  Go问答

将 json 映射到 golang 结构时遇到问题

来源:stackoverflow

时间:2024-04-07 08:27:32 147浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《将 json 映射到 golang 结构时遇到问题》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我有一个 json 流,如下...

[
  {
    "page": 1,
    "pages": 7,
    "per_page": "2000",
    "total": 13200
  },
  [
    {
      "indicator": {
        "id": "sp.pop.totl",
        "value": "population, total"
      },
      "country": {
        "id": "1a",
        "value": "arab world"
      },
      "value": null,
      "decimal": "0",
      "date": "2019"
    },
    {
      "indicator": {
        "id": "sp.pop.totl",
        "value": "population, total"
      },
      "country": {
        "id": "1a",
        "value": "arab world"
      },
      "value": "419790588",
      "decimal": "0",
      "date": "2018"
    },
   ...
   ]
]

我正在尝试解码它......所以我有以下结构......但我不断得到 “无法将数组解组为 struct { p struct ... 类型的 go 值”

type Message []struct {
        P struct {
                Page int
        }
        V []struct {
                Indicator struct {
                        Id    string
                        Value string
                }
                Country struct {
                        Value string
                }
                Value   string
                Decimal string
                Date    string
        }
}

我的结构看起来与 json 匹配...但显然不是!有什么想法吗?


解决方案


由于您的 json 数组有两种不同的类型,因此首先将它们解组到 json.rawmessage 的切片中,即 []byte 作为基础类型,以便我们可以再次解组 json 数组数据。

因此,直接使用索引(预测)解组 pv 结构类型的数据,或检测是否为对象(以“{”开头),然后解组为 p 和数组(以“[”开头),然后解组为 v。现在使用这些数据准备您的消息。

type Message struct {
    PageData P
    ValData  []V
}

type P struct {
    Page int
}

type V struct {
    Indicator struct {
        Id    string
        Value string
    }
    Country struct {
        Value string
    }
    Value   string
    Decimal string
    Date    string
}

func main() {

    var rawdata []json.RawMessage
    json.Unmarshal([]byte(jsonData), &rawdata)
    var pageData P
    json.Unmarshal(rawdata[0], &pageData)
    var valData []V
    json.Unmarshal(rawdata[1], &valData)
    res := Message{pageData, valData}
    fmt.Println(res)
}
var jsonData = `[...]` //your json data

完整代码在Go Playground

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

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