根據 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”屬性的任何值。這些屬性有什么用?有沒有辦法檢測哪個屬性解組失???
1 回答

狐的傳說
TA貢獻1804條經驗 獲得超3個贊
問題僅在我的本地環境中重現。刪除 golang(我用 brew 安裝了 3 個版本)并再次安裝 go 后,它開始按預期工作。Struct
并Field
再次填充。
- 1 回答
- 0 關注
- 215 瀏覽
添加回答
舉報
0/150
提交
取消