Unmarshalling Boolean Values from JSON with Both 0 and False
Parsing JSON data requires careful consideration of data types to avoid misinterpretation. In cases where a service interchanges boolean values as 0 and false (as well as 1 and true), achieving proper unmarshalling becomes crucial.
The inbuilt encoding/json package provides a method to customize the unmarshalling process using custom types. By defining a custom type, you can implement bespoke unmarshalling logic to handle the desired conversion.
Custom Unmarshalling Type
Create a custom type that implements the json.Unmarshaler interface. This type will be responsible for converting JSON data to the desired boolean format.
type ConvertibleBoolean bool func (bit *ConvertibleBoolean) UnmarshalJSON(data []byte) error { asString := string(data) if asString == "1" || asString == "true" { *bit = true } else if asString == "0" || asString == "false" { *bit = false } else { return errors.New(fmt.Sprintf("Boolean unmarshal error: invalid input %s", asString)) } return nil }
In this example, ConvertibleBoolean is a custom boolean type that implements the json.Unmarshaler interface. It overrides the default JSON unmarshalling process and checks the incoming data as a string. If it identifies a string representing true or false (or their numerical counterparts 1 and 0), it sets the ConvertibleBoolean value accordingly. Otherwise, an error is returned.
Using the Custom Type
Now that you have a custom unmarshalling type, use it in a struct to define the expected JSON structure.
type MyType struct { AsBoolean ConvertibleBoolean `json:"field1"` AlsoBoolean ConvertibleBoolean `json:"field2"` }
Example Unmarshalling
With the custom type in place, you can unmarshal JSON data into a MyType struct, correctly converting both 0 and false (as well as 1 and true) to boolean values.
input_json := `{ "field1" : true, "field2" : 1 }` obj := MyType{} json_err := json.Unmarshal([]byte(input_json), &obj) fmt.Printf("%v\n", obj.AsBoolean) //"true" fmt.Printf("%v\n", obj.AlsoBoolean) //"true"
This example JSON data contains "true" and "1", which would be treated as different types by the default unmarshaller. However, by using ConvertibleBoolean, both values are correctly unmarshalled as true.
The above is the detailed content of How to Handle Boolean Unmarshalling from JSON with \'0\' and \'false\' (and \'1\' and \'true\')?. For more information, please follow other related articles on the PHP Chinese website!