代码之家  ›  专栏  ›  技术社区  ›  Patryk

为什么json解析不失败,并将完全不同的类型传递给decode()?

  •  -1
  • Patryk  · 技术社区  · 7 年前

    我有以下数据结构,我想从一个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"}`
    

    不会失败的。为什么?

    完整源代码( 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\n", resp)
    }
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   eugenioy    7 年前

    这是预期的行为 Decode (如 Unmarshal 功能):

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

    默认情况下,忽略没有相应结构字段的对象键。

    但是您可以使用 DisallowUnknownFields() 如果输入json包含目标结构中未包含的字段,则使其失败的函数(如文档中所述)。

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

    在这种情况下,你会得到一个错误,正如你所期望的。

    此处为改装游乐场: https://play.golang.org/p/A0f6dxTXV34