简体   繁体   English

Go:当 json.Unmarshal 到结构时,如何忽略类型不匹配错误?

[英]Go : How to ignore type mismatch error when json.Unmarshal to struct?

Assume I have a struct like假设我有一个像

type A struct {
    Val1 int `json:"val1"`
    Val2 int `json:"val2"`
}

then:然后:

str := `{"val1": "abc", "val2": 2}`
var a A
error := json.Unmarshal([]byte(jsonString),&a)

How can I ingore val1 type mismatch error?如何避免val1类型不匹配错误? I just want to ignore errors when the types don't match, and parse normally if they match.我只想在类型不匹配时忽略错误,如果匹配则正常解析。

How can I ingore val1 type mismatch error?如何避免 val1 类型不匹配错误? I just want to ignore errors when the types don't match, and parse normally if they match.我只想在类型不匹配时忽略错误,如果匹配则正常解析。

You cannot do that.你不能这样做。

The best thing you can do is have the type eg interface{} or json.Number and decide later.您可以做的最好的事情是使用例如interface{}json.Number类型,然后再决定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM