Customizing Serialization
Advanced Serialization Techniques
JSON struct tags offer powerful customization options beyond basic field naming and omission. This section explores advanced serialization techniques in Golang.
Custom Field Conversion
Handling Different Types
type User struct {
ID int `json:"id"`
CreatedAt time.Time `json:"created_at,string"`
Active bool `json:"active,string"`
}
Nested Struct Serialization
type Address struct {
Street string `json:"street"`
City string `json:"city"`
Country string `json:"country"`
}
type Employee struct {
Name string `json:"name"`
Address Address `json:"address"`
}
Serialization Strategies
Strategy |
Tag Option |
Description |
Renaming |
json:"newname" |
Change field name in JSON |
Omitting |
json:"-" |
Exclude field completely |
Conditional |
json:",omitempty" |
Omit if zero value |
Complex Serialization Example
package main
import (
"encoding/json"
"fmt"
"time"
)
type Product struct {
ID int `json:"product_id"`
Name string `json:"product_name"`
Price float64 `json:"price,string"`
CreatedAt time.Time `json:"created_at,omitempty"`
Description string `json:"-"`
}
func main() {
product := Product{
ID: 1,
Name: "Laptop",
Price: 999.99,
CreatedAt: time.Now(),
}
jsonData, _ := json.MarshalIndent(product, "", " ")
fmt.Println(string(jsonData))
}
Serialization Flow
flowchart TD
A[Struct] --> B{Has JSON Tag?}
B -->|Yes| C[Apply Custom Serialization]
B -->|No| D[Default Serialization]
C --> E[Output JSON]
D --> E
Advanced Techniques
Custom Marshalers
func (p *Product) MarshalJSON() ([]byte, error) {
// Custom JSON marshaling logic
}
Handling Unexported Fields
type PrivateData struct {
publicField string `json:"public"`
privateField string `json:"-"`
}
- Minimize complex serialization logic
- Use
json.MarshalIndent()
sparingly
- Prefer
json.Marshal()
for performance-critical code
LabEx Recommendation
At LabEx, we emphasize understanding these serialization techniques to write more flexible and efficient Go code.