简体   繁体   中英

Golang UnmarshalTypeError missing Offset

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

According to the godoc description:

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.

Just like string type unmarshals into chan type,it make a UnmarshalTypeError error,just like the following:

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)
        }
    }
}

Outputs:

UnmarshalTypeError string - chan int - 29

It is working properly!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM