亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 UnmarshalTypeError 獲取失敗字段

從 UnmarshalTypeError 獲取失敗字段

Go
汪汪一只貓 2023-05-15 15:17:39
根據 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 后,它開始按預期工作。StructField再次填充。


查看完整回答
反對 回復 2023-05-15
  • 1 回答
  • 0 關注
  • 215 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號