1
votes

According to GO stdlib, there is an error returned when JSON property type is different than struct's one. Here is definition:

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

Now, I'm trying to simulate a type conversion fail, by having an string field inside struct and providing int to this one.

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

But unfortunately, the error doesn't have any values for "Struct" or "Field" property. What are these properties for? Is there a way to detect at which property unmarshal failed?

1
But they do have values, the error struct is like this: {Value:number Type:string Offset:16 Struct:Sample Field:a_string}, try it on the Go Playground. What is your question? - icza
@icza interesting. Playground gives me a different result comparing to my local one. Will check what's wrong with my environment... - Maxian Nicu
It also works on my local computer, so if you get something else, it must be your environment. What is the output of go version and go env? - icza
go version go1.11.1 darwin/amd64 - Maxian Nicu

1 Answers

2
votes

Issue was reproduced only on my local environment. After removing golang(I had 3 version installed with brew) and installing go once again, it started to work as expected. Struct and Field are populating again.

Also, there is a issue on github GO repository