根据 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
}
现在,我正在尝试模拟类型转换失败,方法是在 struct 中有一个字符串字段并为此提供 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”属性的任何值。这些属性有什么用?有没有办法检测哪个属性解组失败?
狐的传说
相关分类