我得到以下数据:
{
"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
结构的 price
和 amount
对象。如下图
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 规范
关于go - 将 json 解码为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297289/