英文:
Golang UnmarshalTypeError missing Offset
问题
我是你的中文翻译助手,以下是翻译好的内容:
我在使用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)
,但是在JSON包的文档和代码中,它们在UnmarshalTypeError
结构体中有这个变量。
我做错了什么?谢谢。
英文:
I'm totally newbie in Golang and solving problem with parsing JSON. Everything is working, except error handling.
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)
}
}
Here I get error ute.Offset undefined (type *json.UnmarshalTypeError has no field or method Offset)
but in Docs of JSON package and also code they have this variable in UnmarshalTypeError
struct.
What I'm doing wrong? Thank you
答案1
得分: 3
根据godoc的描述:
如果JSON值不适合给定的目标类型,或者JSON数字溢出目标类型,Unmarshal将跳过该字段,并尽可能完成解组。如果没有遇到更严重的错误,Unmarshal将返回描述最早出现的此类错误的UnmarshalTypeError。
就像字符串类型解组为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
它正常工作!
英文:
<p>According to the godoc description:</p>
>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.
<p>Just like <code>string</code> type unmarshals into <code>chan</code> type,it make a <code>UnmarshalTypeError</code> error,just like the following:</p>
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)
}
}
}
<p>Outputs:</p>
UnmarshalTypeError string - chan int - 29
It is working properly!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论