Serialization converts an in-memory value into a representation that can be stored or exchanged; in Go, this conversion is called marshaling. Unmarshaling moves in the other direction, from encoded data into a Go value. These operations let applications process configuration files, APIs, and data exchanged between systems. section 10.5 section 10.5.1
For JSON or XML, use encoding/json or encoding/xml rather than writing a format converter from scratch. Their operations fit into pipelines that read input, validate or transform it, and write the result to a file, network connection, or buffer. section 10.5 section 10.10
For JSON, the shape and behavior of the Go value determine the result:
- Define a struct with exported fields. JSON struct tags map those fields to keys; tags can also omit a field or omit it when empty. section 10.5.1
- Use json.Unmarshal with input bytes and a pointer to the destination value. Handle its error when the input cannot be decoded into that type. section 10.5.1
- Add UnmarshalJSON or MarshalJSON when default field mapping is insufficient—for example, to validate a host URL while reading or redact it while writing. section 10.11 section 10.5.1
Server configuration
A server configuration has fields such as name, debug, port, and host. A matching Go struct maps its JSON keys with tags. Decoding gives the application typed settings; a custom marshaler can replace the host value with "[REDACTED]" in serialized output. section 10.5.1
func (c Config) MarshalJSON() ([]byte, error) {
// Use an anonymous struct to avoid recursion
temp := &struct {
Name string `json:"name"`
Version string `json:"version"`
Debug bool `json:"debug"`
Port int `json:"port"`
Host string `json:"host"`
}{
Name: c.Name,
Version: c.Version,
Debug: c.Debug,
Port: c.Port,
Host: "[REDACTED]", // Redact the host value
}
return json.Marshal(temp)
}
The MarshalJSON listing shows an anonymous struct used to produce redacted JSON without calling the same custom method recursively. section 10.5.1























