Unmarshaling json into a type

后端 未结 2 1427
没有蜡笔的小新
没有蜡笔的小新 2021-01-27 21:19

I get the following data:

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


        
相关标签:
2条回答
  • 2021-01-27 21:35

    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]

    0 讨论(0)
  • 2021-01-27 21:45

    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

    0 讨论(0)
提交回复
热议问题