gpt4 book ai didi

从 UnmarshalTypeError 获取失败字段

转载 作者:IT王子 更新时间:2023-10-29 02:01:07 24 4
gpt4 key购买 nike

根据 GO 标准库,当 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”属性的任何值。这些属性有什么用?有没有办法检测哪个属性解码失败?

最佳答案

问题仅在我的本地环境中重现。删除 golang(我用 brew 安装了 3 个版本)并再次安装 go 后,它开始按预期工作。 StructField 再次填充。

此外,还有一个 issue on github GO repository

关于从 UnmarshalTypeError 获取失败字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53739286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com