Home >Backend Development >Golang >How to Serialize and Deserialize Mixed-Type JSON Arrays in Go?
Serialize a Mixed Type JSON Array in Go
In Go, serializing a mixed type JSON array, containing strings, floats, and Unicode characters, can pose a challenge. While Python allows for arrays of mixed types, Go lacks this feature.
Serialization with MarshalJSON
To customize serialization, Go offers the json.Marshaler interface. By implementing this interface, we can specify how our struct, Row, should be encoded. In this case, we want to encode it as an array of heterogeneous values.
type Row struct { Ooid string Score float64 Text string } func (r *Row) MarshalJSON() ([]byte, error) { arr := []interface{}{r.Ooid, r.Score, r.Text} return json.Marshal(arr) }
MarshalJSON takes an intermediate slice of interface{} to encode the mixed values and returns the encoded JSON bytes.
Deserialization with UnmarshalJSON
To deserialize from JSON bytes back to structs, Go provides the json.Unmarshaler interface.
func (r *Row) UnmarshalJSON(bs []byte) error { arr := []interface{}{} json.Unmarshal(bs, &arr) // TODO: add error handling here. r.Ooid = arr[0].(string) r.Score = arr[1].(float64) r.Text = arr[2].(string) return nil }
UnmarshalJSON uses a similar intermediate slice of interface{} to decode the JSON values and populate the Row struct.
By implementing these interfaces, we gain control over the serialization and deserialization process, allowing us to work with mixed type arrays in Go.
The above is the detailed content of How to Serialize and Deserialize Mixed-Type JSON Arrays in Go?. For more information, please follow other related articles on the PHP Chinese website!