gpt4 book ai didi

json - Golang UnmarshalTypeError 缺少偏移量

转载 作者:IT王子 更新时间:2023-10-29 01:13:18 25 4
gpt4 key购买 nike

我完全是 Golang 的新手,正在解决解析 JSON 的问题。一切正常,除了错误处理。

if err := json.Unmarshal(file, &configData); err != nil {    
if ute, ok := err.(*json.UnmarshalTypeError); ok {
fmt.Printf("UnmarshalTypeError %v - %v - %v", ute.Value, ute.Type, ute.Offset)
}
}

这里我得到错误 ute.Offset undefined (type *json.UnmarshalTypeError has no field or method Offset) 但在 Docs of JSON package还有code他们在 UnmarshalTypeError 结构中有这个变量。

我做错了什么?谢谢

最佳答案

根据godoc描述:

If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshalling as best it can. If no more serious errors are encountered, Unmarshal returns an UnmarshalTypeError describing the earliest such error.

就像string类型解码成chan类型一样,它会产生一个UnmarshalTypeError错误,就像下面这样:

package main

import (
"encoding/json"
"fmt"
)

type A struct {
Name string
Chan chan int
}

func main() {
var a A
bs := []byte(`{"Name":"hello","Chan":"chan"}`)
if e := json.Unmarshal(bs, &a); e != nil {
if ute, ok := e.(*json.UnmarshalTypeError); ok {
fmt.Printf("UnmarshalTypeError %v - %v - %v\n", ute.Value, ute.Type, ute.Offset)
} else {
fmt.Println("Other error:", e)
}
}
}

输出:

UnmarshalTypeError string - chan int - 29

一切正常!

关于json - Golang UnmarshalTypeError 缺少偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35009423/

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