我有以下要从API解析的数据结构:
type OrderBook struct {
Pair string `json:"pair"`
UpdateTime int64 `json:"update_time"`
}
type depthResponse struct {
Result OrderBook `json:"result"`
// doesn't matter here
//Cmd string `json:"-"`
}
当我解析以下内容时:
data := `{"error":{"code":"3016","msg":"交易对错误"},"cmd":"depth"}`
它不会失败。为什么?
完整的源代码(游乐场)
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
)
type OrderBook struct {
Pair string `json:"pair"`
UpdateTime int64 `json:"update_time"`
}
type depthResponse struct {
Result OrderBook `json:"result"`
}
func main() {
data := `{"error":{"code":"3016","msg":"交易对错误"},"cmd":"depth"}`
r := strings.NewReader(data)
var resp depthResponse
if err := json.NewDecoder(r).Decode(&resp); err != nil {
log.Fatalf("We should end up here: %v", err)
}
fmt.Printf("%+v\n", resp)
}
这是预期的行为Decode
(如Unmarshal
函数中所述):
https://golang.org/pkg/encoding/json/#Unmarshal
默认情况下,没有相应结构字段的对象键将被忽略。
但是DisallowUnknownFields()
,如果输入JSON的目标结构中未包含字段,则可以使用该函数(也如文档中所述)使其失败。
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()
在这种情况下,您将得到预期的错误。
此处修改过的游乐场:https : //play.golang.org/p/A0f6dxTXV34
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句