Unmarshaling json into a type

2020-05-06 14:17发布

I get the following data:

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

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: cannot unmarshal string into Go struct field OrderBookResult.bids of type feed.OrderBookItem

When I change the struct into

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

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

标签: go struct
2条回答
2楼-- · 2020-05-06 15:03

As the error says:

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

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

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

Playground working example

For more information read GoLang spec for Unmarshaler

查看更多
Juvenile、少年°
3楼-- · 2020-05-06 15:16

You are treating your bids as a structure of two separate strings, when they are really a slice of strings in the JSON. If you change OrderBookItem to be

type OrderBookItem []string

which is how you have defined them in the second bit, which works.

To access the values you just have to do: price := d.Bids[0] amount := d.Bids[1]

查看更多
登录 后发表回答