Decoder

There two ways of decoding data in JSONā€”the first is the json.Unmarshal function that uses a byte slice as input, and the second is the json.Decoder type that uses a generic io.Reader to get the encoded content. We will use the latter in our examples because it will enable us to work with structs such as strings.Reader. Another advantage of the decoder is the customization that can be done with the following methods:

  • DisallowUnknownFields: The decode will return an error if a field that is unknown to the receiving data structure is found.
  • UseNumber: Numbers will be stored as json.Number instead of float64.

This is a practical example of data decoding using the json.Decoder type:

r := strings.NewReader(`{
"name":"Lavinia",
"surname":"Whateley",
"year_of_birth":1878
}`)
d := json.NewDecoder(r)
var c Character
if err := d.Decode(&c); err != nil {
log.Fatalln(err)
}
log.Printf("%+v", c)

The full example is available here: https://play.golang.org/p/a-qt5Mk9E_J.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.135.80