我得到以下数据:
{ "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:无法将字符串解组到类型为feed.OrderBookItem的Go结构字段OrderBookResult.bids中
当我将结构更改为
type OrderBookResult struct { Timestamp string `json:"timestamp"` Bids [][]string `json:"bids"` Asks [][]string `json:"asks"` }
有用。我希望将它们定义为float64它们是什么。我必须改变什么?
float64
如错误所示:
我们不能将作为字符串切片的OrderBookResult.bids转换为struct的OrderBookItem
实现UnmarshalJSON接口转换数组的对象price和amount的OrderBookItem结构。像下面
UnmarshalJSON
price
amount
OrderBookItem
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的 GoLang规范