arrays - Golang : Parsing two array of arrays in JSON, 使用相同的结构

标签 arrays json parsing go

<分区>

假设我有这个数据:

{
"code": 10000,
"msg": "Successful request processing",
"asks": [ 
    [
        "0.03434400",
        "0.31100000"
    ],
    [
        "0.03436300",
        "0.18900000"
    ],
    [

],
"bids": [ 
    [
        "0.03427400", 
        "0.21100000"  
    ],...

感谢 Go to JSON 转换器,我知道它可以像这样解析(在我的脚本中工作):

type AutoGenerated struct {
Code int        `json:"code"`
Msg  string     `json:"msg"`
Asks [][]string `json:"asks"`
Bids [][]string `json:"bids"`
}

我宁愿这样解析它:

type Box struct {
Number int `json:"code"`
Message string `json:"msg"` 
Asks []MarketData `json:"asks"`
Bids []MarketData  `json:"bids"`
}

type MarketData struct {
Sell []string
}

或者,更好的是,这个(假设 Box 结构保持不变):

type MarketData struct {
SellPrice string
SellQuantity string
}

问题是,如果我尝试使用 price :=response.Asks[0].SellPrice 或使用前面的示例 response.Asks[0].Sell 来打印上面的内容,我会得到一个空结构。

为什么这行不通?对我来说,这似乎是合法的。它构建良好,但每当我尝试运行它时,它都会打印空括号。

最佳答案

package main

import (
    "encoding/json"
    "fmt"
)

var j = `{
    "code": 10000,
    "msg": "Successful request processing",
    "asks": [ 
        [
            "0.03434400",
            "0.31100000"
        ],
        [
            "0.03436300",
            "0.18900000"
        ]


    ],
    "bids": [ 
        [
            "0.03427400", 
            "0.21100000"  
        ]
        ]
    }
        `

type Box struct {
    Number  int          `json:"code"`
    Message string       `json:"msg"`
    Asks    []MarketData `json:"asks"`
    Bids    []MarketData `json:"bids"`
}

type MarketData struct {
    SellPrice    string
    SellQuantity string
}

func (md *MarketData) UnmarshalJSON(d []byte) error {
    val := []string{}
    err := json.Unmarshal(d, &val)
    if err != nil {
        return err
    }
    if len(val) != 2 {
        return fmt.Errorf("MarketData unmarshal error len != 2")
    }
    md.SellPrice = val[0]
    md.SellQuantity = val[1]
    return nil
}

func main() {
    ins := new(Box)
    err := json.Unmarshal([]byte(j), ins)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", ins)
}

https://play.golang.org/p/EKH3ICJJuZ_W

关于arrays - Golang : Parsing two array of arrays in JSON, 使用相同的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860061/

相关文章:

java - 有效地从 HTTP GET 响应中提取 div 标签中的特定信息

java - 字符数组需要按一定的顺序和位置显示

Javascript将数组分配给另一个数组的元素

javascript - JSON 数组 - 删除第一个元素

C# 和正则表达式 : How to extract strings between quotation marks

c++ - 如何显示功能的开始,结束行和功能体?

java - 就内存使用而言,使用 float[] 数组还是 16 个 float 哪个更好?

javascript - .slice.call 与 .push 在 javascript 中

PHP Json_encode - MySQL 特定列上没有 json 数据

javascript - JSON api时间戳+数据解析