How to Serialize a Mixed Type JSON Array in Go
Challenge
Creating a JSON array that represents heterogenous data, such as a mix of strings, floating point numbers, and unicode characters, can be challenging in Go due to its lack of support for mixed types in arrays.
Solution
To overcome this limitation, we can leverage Go's customizable JSON serialization mechanism by implementing the json.Marshaler and json.Unmarshaler interfaces. By defining these functions on our custom type, we gain control over how our data is serialized and deserialized.
Serialization (Marshaling)
To serialize our mixed-type data into a JSON array, we create a MarshalJSON function for our custom type. In this function, we create an intermediate slice of interface{} elements and fill it with the values we want to serialize. We then use the json.Marshal function on the slice to generate the JSON representation of our data.
Deserialization (Unmarshaling)
Similarly, for deserialization, we create an UnmarshalJSON function. Here, we first use the json.Unmarshal function to parse the incoming JSON bytes into the intermediate slice of interface{} elements. We then manually extract the values from the slice and assign them to the fields of our custom type.
Example
The following example demonstrates how to serialize and deserialize a mixed-type data structure:
package main import ( "encoding/json" "fmt" ) 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) } func main() { rows := []Row{ {"ooid1", 2.0, "Söme text"}, {"ooid2", 1.3, "Åther text"}, } marshalled, _ := json.Marshal(rows) fmt.Println(string(marshalled)) }
Conclusion
By implementing json.Marshaler and json.Unmarshaler interfaces, we gain the flexibility to handle mixed-type data structures in Go. This approach allows us to customize the serialization and deserialization process, producing the desired JSON array format.
The above is the detailed content of How to Serialize Mixed-Type JSON Arrays in Go?. For more information, please follow other related articles on the PHP Chinese website!