Sling Academy
Home/Golang/Serializing and Deserializing Custom Types in Go

Serializing and Deserializing Custom Types in Go

Last updated: November 26, 2024

Go is a powerful language that provides a variety of ways to work with data, including serialization and deserialization. Serialization is the process of converting a Go object into a format that can be easily stored or transmitted, while deserialization is the reverse process. This article will guide you through serializing and deserializing custom types in Go using JSON and gob packages.

JSON Serialization and Deserialization

The Go standard library provides excellent support for JSON with the encoding/json package. This package allows you to easily convert Go structs to JSON and vice versa.

Defining a Custom Type

Let’s start by defining a custom type that we will serialize. We'll create a simple struct to represent a person.

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

Serializing to JSON

To serialize an instance of Person to a JSON string, we use the json.Marshal function:

import (
    "encoding/json"
    "fmt"
)

func main() {
    p := Person{Name: "Alice", Age: 30}

    jsonData, err := json.Marshal(p)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(jsonData))
}

The output will be:

{"name":"Alice","age":30}

Deserializing from JSON

Deserializing JSON into a Go struct is straightforward using json.Unmarshal. Given a JSON string, you can populate a Person struct as follows:

func main() {
    jsonString := `{"name":"Bob","age":25}`
    var p Person

    err := json.Unmarshal([]byte(jsonString), &p)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(p)
}

The output will be:

{Name:Bob Age:25}

Gob Serialization and Deserialization

Go’s encoding/gob package is more suitable for serializing data that will be consumed by other Go applications, as it encodes the data in a binary format specific to Go types.

Serializing with Gob

To use gob, we have to encode our data to a binary format which is then stored or transmitted:

import (
    "bytes"
    "encoding/gob"
    "fmt"
)

func main() {
    var buf bytes.Buffer
    enc := gob.NewEncoder(&buf)

    p := Person{Name: "Charlie", Age: 35}
    err := enc.Encode(p)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(buf.Bytes())
}

Deserializing with Gob

You can deserialize the binary data back into a Go struct by using the gob.Decoder:

func main() {
    var buf bytes.Buffer
    var data = []byte{ /* assume gob-encoded data here */ }
    buf.Write(data)

    var p Person
    dec := gob.NewDecoder(&buf)
    err := dec.Decode(&p)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(p)
}

Keep in mind that the structure of the Person type must be the same as the one used for encoding.

Conclusion

Serialization and deserialization are crucial for data exchange in distributed systems. Go’s built-in packages like encoding/json and encoding/gob provide robust mechanisms for handling these tasks. Choose JSON when dealing with web services or APIs where versatility across platforms is needed, and gob when you optimize within Go-controlled environments.

Next Article: Working with Protocol Buffers (gRPC) in Go

Previous Article: Handling URL Encoding and Decoding in Go

Series: Data Serialization and Encoding in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant