将JSON解组为类型 [英] Unmarshaling json into a type

查看:77
本文介绍了将JSON解组为类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到以下数据:

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

通过websocket,我想将其解组为

via websocket and I would like to unmarshall it into

type OrderBookItem struct {
    Price  string
    Amount string
}

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

使用以下命令将其解组:

Unmarshal it with:

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

但我不断收到错误消息:

But I keep getting the error:

json:无法将字符串解组到Go struct字段中 feed.OrderBookItem类型的OrderBookResult.bids

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,这就是它们.我必须更改什么?

it works. I would like them to be defined as float64 which is what they are. What do I have to change?

推荐答案

错误提示:

json:无法将字符串解组到Go struct字段中 feed.OrderBookItem类型的OrderBookResult.bids

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

我们无法将作为字符串切片的OrderBookResult.bids转换为结构的OrderBookItem

We cannot convert OrderBookResult.bids which is a slice of string into OrderBookItem which is struct

实现UnmarshalJSON接口可将数组转换为OrderBookItem结构的priceamount的对象.像下面一样

Implement UnmarshalJSON interface to convert array into objects for price and amount of OrderBookItem struct. Like below

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)
}

操场上的工作示例

有关更多信息,请阅读 Unmarshaler

For more information read GoLang spec for Unmarshaler

这篇关于将JSON解组为类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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