dourang8305 2018-06-03 19:51
浏览 90
已采纳

为什么JSON解析不会因传递给Decode()的类型完全不同而失败?

I have the following data structures which I'd like to parse from an 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:"-"`
}

and when I parse the following:

data := `{"error":{"code":"3016","msg":"交易对错误"},"cmd":"depth"}`

It doesn't fail. Why?

Full source code (playground)

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
", resp)
}
  • 写回答

1条回答 默认 最新

  • dqf2015 2018-06-03 20:05
    关注

    That's the expected behaviour of Decode (as documented in the Unmarshal function):

    https://golang.org/pkg/encoding/json/#Unmarshal

    By default, object keys which don't have a corresponding struct field are ignored.

    You can however use the DisallowUnknownFields() function (as described in the docs as well) to have it fail if the input JSON has fields not contained in the destination struct.

    dec := json.NewDecoder(r)
    dec.DisallowUnknownFields()
    

    In that case, you'll get an error as you expect.

    Modified playground here: https://play.golang.org/p/A0f6dxTXV34

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?