如何将具有两种不同数据类型的JSON数组解析为Golang中的结构 [英] How to parse JSON arrays with two different data types into a struct in Golang

查看:52
本文介绍了如何将具有两种不同数据类型的JSON数组解析为Golang中的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的JSON:

I have JSON that looks like this:

{
    "a": [
          [
              "12.58861425",
              10.52046452
          ],
          [
              "12.58861426",
              4.1073
          ]
        ]
    "b": [
          [
              "12.58861425",
              10.52046452
          ],
          [
              "12.58861426",
              4.1073
          ]
        ]
    "c": "true"
    "d": 1234
}
        

我想将其解编为我创建的结构:

I want to unmarshall this into a struct I created:

type OrderBook struct {
	A [][2]float32 `json:"a"`
	B [][2]float32 `json:"b"`
        C string `json:"c"`
	D uint32 `json:"d"`
}

//Note this won't work because the JSON array contains a string and a float value pair rather than only floats.

通常,我通常将这样的JSON转换为Golang中的结构:

Normally I would then convert this JSON into a struct in Golang as so:

orders := new(OrderBook)
err = json.Unmarshal(JSON, &orders)

由于我无法定义类型结构以匹配JSON,因此无法使用.进行一些阅读后,我认为解组到接口中,然后通过类型检查使用接口数据可能是一种解决方案.

Since I can't define the type struct to match the JSON this won't work. Doing a bit of reading, I think Unmarshal-ing into an interface, and then using the interface data through type checking may be a solution.

我要朝这个正确的方向前进吗?
一个显示数据一旦进入界面后我将如何使用它的模板确实会有所帮助.

Am I going in the right direction with this?
A template showing how I might go about using the data once it's in the interface would really help.

推荐答案

为什么不仅仅像这样声明A和B切片的类型呢?

Why not just leave out declaring the types of the A and B slices like so?

data := []byte(`{"a": [["12.58861425",10.52046452],["12.58861426",4.1073]],"b": [["12.58861425",10.52046452],["12.58861426",4.1073]],"c": "true","d": 1234}`)

type OrderBook struct {
    A [][2]interface{} `json:"a"`
    B [][2]interface{} `json:"b"`
    C string           `json:"c"`
    D uint32           `json:"d"`
}
orders := new(OrderBook)
err := json.Unmarshal(data, &orders)
if err != nil {
    fmt.Printf(err.Error())
} else {
    fmt.Printf("%s\n", orders.A[0][0].(string))     
    fmt.Printf("%f\n", orders.A[0][1].(float64))
}

操场上有个例子: https://play.golang.org/p/0MUY -yOYII

我必须不同意evanmcdonnal,在某些用例中,滚动自己的Unmarshaller是有意义的,我不认为这是其中之一.没有比这里显示的要简单的多了.

I must disagree with evanmcdonnal, there are certainly use cases where where rolling your own Unmarshaller makes sense, this I do not believe is one of them. It doesn't get much simpler than what is shown here.

这篇关于如何将具有两种不同数据类型的JSON数组解析为Golang中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆