dourang8305
dourang8305
2018-06-03 19:51

为什么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 dqf2015 3年前

    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

    点赞 评论 复制链接分享