Encoding and Serialization
Overview
Go provides standard encoding packages for JSON, XML, and binary data.
JSON
import "encoding/json"
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Age int `json:"-"` // Ignored
}
// Encode
user := User{Name: "Alice", Email: "a@b.com"}
data, _ := json.Marshal(user)
// {"name":"Alice","email":"a@b.com"}
// Decode
var u User
json.Unmarshal(data, &u)
// Pretty print
data, _ := json.MarshalIndent(user, "", " ")Streaming JSON
// Encode to writer
encoder := json.NewEncoder(w)
encoder.Encode(user)
// Decode from reader
decoder := json.NewDecoder(r)
decoder.Decode(&user)XML
import "encoding/xml"
type Person struct {
XMLName xml.Name `xml:"person"`
Name string `xml:"name"`
Age int `xml:"age,attr"`
}
data, _ := xml.MarshalIndent(person, "", " ")
xml.Unmarshal(data, &p)Gob (Go Binary)
import "encoding/gob"
// Encode
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
enc.Encode(data)
// Decode
dec := gob.NewDecoder(&buf)
dec.Decode(&result)CSV
import "encoding/csv"
// Write
w := csv.NewWriter(file)
w.Write([]string{"a", "b", "c"})
w.Flush()
// Read
r := csv.NewReader(file)
records, _ := r.ReadAll()Base64
import "encoding/base64"
encoded := base64.StdEncoding.EncodeToString(data)
decoded, _ := base64.StdEncoding.DecodeString(encoded)Summary
| Package | Format |
|---|---|
encoding/json |
JSON |
encoding/xml |
XML |
encoding/gob |
Go binary |
encoding/csv |
CSV |
encoding/base64 |
Base64 |