Home >Backend Development >Golang >How to Serialize a Mixed-Type JSON Array in Go?

How to Serialize a Mixed-Type JSON Array in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-11 09:29:10124browse

How to Serialize a Mixed-Type JSON Array in Go?

Serialize a Mixed Type JSON Array in Go

In Go, serializing a heterogenous array of strings, floating point numbers, and unicode characters into a JSON array might seem challenging due to the lack of built-in support for mixed type arrays. However, by implementing the json.Marshaler interface, we can customize how objects are serialized to achieve this.

Implementing the MarshalJSON Method

To serialize a structure like Row as an array of arrays, we create a MarshalJSON method on the Row type. This method converts the Row struct into an array of generic interface values and then serializes them using json.Marshal:

func (r *Row) MarshalJSON() ([]byte, error) {
    arr := []interface{}{r.Ooid, r.Score, r.Text}
    return json.Marshal(arr)
}

Example Usage

With the MarshalJSON method in place, we can serialize a slice of Row elements into a valid JSON array:

rows := []Row{{"ooid1", 2.0, "Söme text"}, {"ooid2", 1.3, "Åther text"}}
marshalled, _ := json.Marshal(rows)

// Output:
// {"results": [["ooid1", 2.0, "Söme text"], ["ooid2", 1.3, "Åther text"]]}

Unmarshaling from JSON

If needed, we can also implement the json.Unmarshaler interface to deserialize JSON data back into Row structs. This involves a similar approach of using an intermediate slice of interface values to store the values extracted from the JSON array:

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
}

By implementing the json.Marshaler and json.Unmarshaler interfaces, we can effectively serialize and deserialize mixed type arrays in Go, enabling us to manipulate data structures with heterogenous elements as JSON.

The above is the detailed content of How to Serialize a Mixed-Type JSON Array in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn