Object Serialization in Go (Golang): From JSON to Protobuf
Serialization (marshaling) is the process of converting a data structure (object) into a byte sequence for transmission over a network or storage on disk. The reverse process is deserialization (unmarshaling). In Go, this task is handled by standard and third-party packages. Let's look at the main approaches.
1. Standard Library: encoding/json
The most popular method. The encoding/json package is used for serialization.
Basic Example
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 (Marshal) jsonData, err := json.Marshal(user) if err != nil { log.Fatal(err) } fmt.Println(string(jsonData)) // {"id":1,"name":"Alice","email":"alice@example.com"}
// Deserialization (Unmarshal) var decoded User err = json.Unmarshal(jsonData, &decoded) if err != nil { log.Fatal(err) } fmt.Printf("%+v", decoded) // {ID:1 Name:Alice Email:alice@example.com}}Important Struct Tags
json:"field_name"— sets the field name in JSON,omitempty— omits the field if it is empty (e.g., empty string, 0, nil),string— forces a string representation for numeric fields-— ignores the field during serialization
2. XML Serialization: encoding/xml
The encoding/xml package works on a similar principle but uses XML tags.
package main
import ( "encoding/xml" "fmt")
type Person struct { XMLName xml.Name `xml:"person"` Name string `xml:"name"` Age int `xml:"age,attr"`}
func main() { p := Person{Name: "Bob", Age: 30} xmlData, _ := xml.MarshalIndent(p, "", " ") fmt.Println(string(xmlData)) // Output: // <person age="30"> // <name>Bob</name> // </person>}Attributes (,attr), nested elements, CDATA, and namespaces are supported.
3. Binary Serialization: encoding/gob
The gob package is Go's own format for binary serialization. It is ideal for data exchange between Go applications.
package main
import ( "bytes" "encoding/gob" "fmt" "log")
type Data struct { X, Y int Label string}
func main() { var buf bytes.Buffer enc := gob.NewEncoder(&buf) data := Data{X: 10, Y: 20, Label: "test"}
// Encoding if err := enc.Encode(data); err != nil { log.Fatal(err) }
// Decoding var decoded Data dec := gob.NewDecoder(&buf) if err := dec.Decode(&decoded); err != nil { log.Fatal(err) } fmt.Printf("%+v", decoded) // {X:10 Y:20 Label:test}}gob features:
- Requires prior registration of types (if interfaces are used)
- More compact than JSON for binary data
- Not supported by other languages (Go only)
4. Protocol Buffers (protobuf)
Google's protocol for efficient binary serialization. Requires installing protoc and the protoc-gen-go plugin.
Step 1: Define the schema (user.proto)
syntax = "proto3";package main;
message User { int32 id = 1; string name = 2; string email = 3;}Step 2: Generate code
protoc --go_out=. user.proto
Also in library
Recommendations