Согласно GO stdlib, возвращается ошибка, когда тип свойства JSON отличается от типа структуры.Вот определение:
// 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
}
Теперь я пытаюсь смоделировать сбой преобразования типа, имея строковое поле внутри структуры и предоставляя ему int.
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)
}
}
Нок сожалению, ошибка не имеет значений для свойства "Struct" или "Field".Для чего эти свойства?Есть ли способ определить, при каком свойстве unmarshal не удалось?