Home >Backend Development >Golang >How to Serialize and Deserialize Heterogeneous JSON Arrays in Go?

How to Serialize and Deserialize Heterogeneous JSON Arrays in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 14:57:10461browse

How to Serialize and Deserialize Heterogeneous JSON Arrays in Go?

Serializing Heterogeneous JSON Arrays in Go

In Go, serializing heterogeneous JSON arrays (containing a mix of strings, numbers, and unicode characters) poses a challenge due to the language's prohibition on mixed type slices. Consider the following desired JSON structure:

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

Serialization with a Marshaler Interface

To customize serialization, we can implement the json.Marshaler interface for our Row type. We'll use an intermediate slice of interface{} to encode the heterogeneous values:

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)
}

In this example, the MarshalJSON method converts the Row to an array of mixed types.

Deserialization with an Unmarshaler Interface

We can similarly implement the json.Unmarshaler interface to destructure the heterogeneous values:

func (r *Row) UnmarshalJSON(bs []byte) error {
    arr := []interface{}{}
    json.Unmarshal(bs, &arr)
    r.Ooid = arr[0].(string)
    r.Score = arr[1].(float64)
    r.Text = arr[2].(string)
    return nil
}

This method converts the JSON bytes back into our Row structure.

The above is the detailed content of How to Serialize and Deserialize Heterogeneous JSON Arrays 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