当前位置: > > > > 从 UnmarshalTypeError 获取失败字段
来源:stackoverflow
2024-04-22 11:36:34
0浏览
收藏
哈喽!今天心血来潮给大家带来了《从 UnmarshalTypeError 获取失败字段》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!
问题内容
根据 go stdlib,当 json 属性类型与结构体类型不同时,会返回错误。定义如下:
// an unmarshaltypeerror describes a json value that was // not appropriate for a value of a specific go type. type unmarshaltypeerror struct { value string // description of json value - "bool", "array", "number -5" type reflect.type // type of go value it could not be assigned to offset int64 // error occurred after reading offset bytes struct string // name of the struct type containing the field field string // name of the field holding the go value }
现在,我尝试通过在结构体中包含一个字符串字段并向该字段提供 int 来模拟类型转换失败。
import ( "encoding/json" "fmt" ) type Sample struct { StringProp string `json:"a_string"` } func main(){ jsonString := `{ "a_string" : 1 }` s := Sample{} err := json.Unmarshal([]byte(jsonString), &s) if err != nil { typeErr := err.(*json.UnmarshalTypeError) fmt.Print(typeErr.Field) } }
但不幸的是,该错误没有任何“struct”或“field”属性值。这些属性有什么用? 有没有办法检测哪个属性解组失败?
解决方案
问题仅在我的本地环境中重现。删除golang(我用brew安装了3个版本)并再次安装go后,它开始按预期工作。 Struct
和 Field
正在再次填充。
还有一个
今天关于《从 UnmarshalTypeError 获取失败字段》的内容介绍就到此结束,如果有什么疑问或者建议,可以在公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!