Nik*_*kel 4 json go unmarshalling
我的 JSON 看起来像这样:
{
"a": [
[
"12.58861425",
10.52046452
],
[
"12.58861426",
4.1073
]
]
"b": [
[
"12.58861425",
10.52046452
],
[
"12.58861426",
4.1073
]
]
"c": "true"
"d": 1234
}
Run Code Online (Sandbox Code Playgroud)
我想将其解组到我创建的结构中:
type OrderBook struct {
A [][2]float32 `json:"a"`
B [][2]float32 `json:"b"`
C string `json:"c"`
D uint32 `json:"d"`
}
//Note this won't work because the JSON array contains a string and a float value pair rather than only floats.Run Code Online (Sandbox Code Playgroud)
通常我会将此 JSON 转换为 Golang 中的结构,如下所示:
orders := new(OrderBook)
err = json.Unmarshal(JSON, &orders)Run Code Online (Sandbox Code Playgroud)
由于我无法定义类型结构来匹配 JSON,所以这是行不通的。做了一些阅读,我认为解组到接口中,然后通过类型检查使用接口数据可能是一个解决方案。
我的方向正确吗?
一个显示数据进入界面后我如何使用数据的模板将会非常有帮助。
为什么不像这样省略声明 A 和 B 切片的类型呢?
data := []byte(`{"a": [["12.58861425",10.52046452],["12.58861426",4.1073]],"b": [["12.58861425",10.52046452],["12.58861426",4.1073]],"c": "true","d": 1234}`)
type OrderBook struct {
A [][2]interface{} `json:"a"`
B [][2]interface{} `json:"b"`
C string `json:"c"`
D uint32 `json:"d"`
}
orders := new(OrderBook)
err := json.Unmarshal(data, &orders)
if err != nil {
fmt.Printf(err.Error())
} else {
fmt.Printf("%s\n", orders.A[0][0].(string))
fmt.Printf("%f\n", orders.A[0][1].(float64))
}
Run Code Online (Sandbox Code Playgroud)
操场上有一个例子:https ://play.golang.org/p/0MUY-yOYII
我必须不同意 evamcdonnal 的观点,确实在某些用例中,滚动自己的 Unmarshaller 是有意义的,但我不认为这是其中之一。它并不比这里显示的更简单。
| 归档时间: |
|
| 查看次数: |
6455 次 |
| 最近记录: |