Object Serialization in Go (Golang): From JSON to Protobuf
Serialization is the process of converting a data structure (object, slice, map) into a sequence of bytes for saving to a file, transmitting over a network, or caching. The reverse process is deserialization. In Go (Golang), this task is solved using built-in packages and third-party libraries. The choice of tool depends on requirements for speed, data size, readability, and compatibility with other languages.
1. Built-in encoding/json Package
The most popular serialization method in Go. JSON is a human-readable, cross-platform format. The encoding/json package provides the Marshal and Unmarshal functions.
package main
import ( "encoding/json" "fmt" "log")
type User struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email,omitempty"`}
func main() { user := User{ID: 1, Name: "Alice", Email: "alice@example.com"}
// Serialization jsonData, err := json.Marshal(user) if err != nil { log.Fatal(err) } fmt.Println(string(jsonData)) // {"id":1,"name":"Alice","email":"alice@example.com"}
// Deserialization var decoded User err = json.Unmarshal(jsonData, &decoded) if err != nil { log.Fatal(err) } fmt.Printf("%+v", decoded)}Features:
- Support for struct tags to customize field names.
- Works with slices, maps, and nested structures.
- Slower than binary formats, but convenient for debugging.
- Does not support circular references.
2. encoding/xml — XML Serialization
XML is used in SOAP, RSS, and configuration files. The encoding/xml package works similarly to JSON, but with xml tags.
type Book struct { Title string `xml:"title"` Author string `xml:"author"` Pages int `xml:"pages,attr"`}
func main() { book := Book{Title: "Go in Action", Author: "William Kennedy", Pages: 500} xmlData, _ := xml.MarshalIndent(book, "", " ") fmt.Println(string(xmlData)) // <Book pages="500"> // <title>Go in Action</title> // <author>William Kennedy</author> // </Book>}When to use:
- Integration with legacy systems.
- Strict schemas (XSD).
- Document-oriented data.
3. encoding/gob — Native Binary Format for Go
The encoding/gob package is designed specifically for Go. It efficiently encodes data into a binary format and supports complex types (interfaces, channels, functions — with limitations).
import "encoding/gob"
type Task struct { ID int Status string}
func main() { var network bytes.Buffer enc := gob.NewEncoder(&network) dec := gob.NewDecoder(&network)
task := Task{ID: 42, Status: "done"} err := enc.Encode(task) if err != nil { log.Fatal(err) }
var restored Task err = dec.Decode(&restored) fmt.Println(restored) // {42 done}}Advantages:
- High speed and compactness.
- Automatic type registration.
- Support for circular structures.
Disadvantage: incompatibility with other languages.
4. Protocol Buffers (protobuf) — Fast Binary Serialization
Developed by Google. Requires defining a schema in a .proto file and generating code via protoc. The google.golang.org/protobuf library is the modern standard.
// user.proto// syntax = "proto3";// message User {// int32 id = 1;// string name = Also in library
Parsing HTML in PHP: DOMDocument, SimpleXML, and cURL for Web Scraping
ORM for C++: Comparison and Usage Examples
Monitoring Rust Applications: Libraries and Tools for Performance Tracking
Swift WebSocket Libraries: Starscream and URLSessionWebSocketTask