go - 将 json 解码为类型

标签 go struct

我得到以下数据:

{
  "timestamp": "1526058949",
  "bids": [
    [
      "7215.90",
      "2.31930000"
    ],
    [
      "7215.77",
      "1.00000000"
    ]
  ]
}

通过 websocket,我想将其解码为

type OrderBookItem struct {
    Price  string
    Amount string
}

type OrderBookResult struct {
    Timestamp string            `json:"timestamp"`
    Bids      []OrderBookItem `json:"bids"`
    Asks      []OrderBookItem `json:"asks"`
}

解码它:

s := e.Data.(string)
d := &OrderBookResult{}
err := json.Unmarshal([]byte(s), d)
if err == nil {
 ....
} else {
 fmt.Println(err.Error())
}

但我一直收到错误:

json: cannot unmarshal string into Go struct field OrderBookResult.bids of type feed.OrderBookItem

当我将结构更改为

type OrderBookResult struct {
        Timestamp string     `json:"timestamp"`
        Bids      [][]string `json:"bids"`
        Asks      [][]string `json:"asks"`
} 

它有效。我希望将它们定义为 float64,它们就是这样。我需要更改什么?

最佳答案

如错误所述:

json: cannot unmarshal string into Go struct field OrderBookResult.bids of type feed.OrderBookItem

我们无法将字符串片段 OrderBookResult.bids 转换为结构体 OrderBookItem

实现 UnmarshalJSON 接口(interface),将数组转换为 OrderBookItem 结构的 priceamount 对象。如下图

package main

import (
    "fmt"
    "encoding/json"
)

type OrderBookItem struct {
    Price  string
    Amount string
}

func(item *OrderBookItem) UnmarshalJSON(data []byte)error{
    var v []string
    if err:= json.Unmarshal(data, &v);err!=nil{
        fmt.Println(err)
        return err
    }
    item.Price  = v[0]
    item.Amount = v[1]
    return nil
}

type OrderBookResult struct {
    Timestamp string            `json:"timestamp"`
    Bids      []OrderBookItem   `json:"bids"`
    Asks      []OrderBookItem   `json:"asks"`
}

func main() {
    var result OrderBookResult
    jsonString := []byte(`{"timestamp": "1526058949", "bids": [["7215.90", "2.31930000"], ["7215.77", "1.00000000"]]}`)
    if err := json.Unmarshal([]byte(jsonString), &result); err != nil{
        fmt.Println(err)
    }
    fmt.Printf("%+v", result)
}

Playground working example

有关更多信息,请阅读 Unmarshaler 的 GoLang 规范

关于go - 将 json 解码为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297289/

相关文章:

pointers - 从非 chan 类型接收 *bool

c - Memset 结构指针导致空检查失败

c - 错误 : invalid use of undefined type ‘struct Item’

在 C 中为未知(大小)结构创建缓冲区

go - Golang for似乎正在跳过某些实体

json - 如何将双引号中的内容与 golang 中的正则表达式进行匹配?

c - 对内核模块导出函数的 undefined reference

c - 结构中的 "warning: useless storage class specifier in empty declaration"

golang 导入包内包

go - Gorm v2 外键上的多对多错误