我在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
struct中有这个变量。
我做错了什么?谢谢
答案 0 :(得分:1)
根据godoc描述:
如果JSON值不适合给定的目标类型,或者如果JSON编号溢出目标类型,则Unmarshal会跳过该字段并尽可能完成解组。如果没有遇到更严重的错误,Unmarshal将返回描述最早此类错误的UnmarshalTypeError。
就像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
工作正常!