E altri esempi quando json.Unmarshal()
restituisce un errore (inoltre specif ying un JSON valido):
Specifica di un nil
o empty
fetta:
i := 0
err := json.Unmarshal(nil, &i)
fmt.Println(err) // unexpected end of JSON input
Specifica di un non-puntatore unmarshal in:
err = json.Unmarshal([]byte(`{"name":"a"}`), i)
fmt.Println(err) // json: Unmarshal(non-pointer int)
Specifica nil
come puntatore porta:
err = json.Unmarshal([]byte(`{"name":"a"}`), nil)
fmt.Println(err) // json: Unmarshal(nil)
Specificare i numeri JSON th a traboccherebbe il tipo di bersaglio. Citando il doc di json.Unmarshal()
:
Se un valore JSON non è appropriato per un determinato tipo di bersaglio, o se un numero JSON trabocca il tipo di destinazione, Unmarshal salta quel campo e completa l'unmarshalling nel miglior modo possibile. Se non si verificano più errori gravi, Unmarshal restituisce un errore UnmarshalType che descrive il primo errore di questo tipo.
per dimostrare questo:
var j int8
err = json.Unmarshal([]byte(`1112`), &j)
fmt.Println(err) // json: cannot unmarshal number 1112 into Go value of type int8
Volete fare un esempio che funzioni, o almeno compila, [come questo] (http://play.golang.org/p/ywOPSds8zQ). 'Unmarshal' restituirà un errore quando l'input non è valido JSON (come, cambia' false' in 'hello', o rimuovi la parentesi chiusa). – twotwotwo
È tutto open source, puoi sempre controllare anche l'implementazione di Unmarshal: https://golang.org/src/encoding/json/decode.go?s=2621:2669#L64 (e checkValid: https://golang.org) /src/encoding/json/scanner.go?s=732:781#L16) –