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

How to Serialize Mixed-Type JSON Arrays in Go?

Patricia Arquette
Release: 2024-12-07 07:01:12
Original
257 people have browsed it

How to Serialize Mixed-Type JSON Arrays in Go?

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))
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template