JSON Custom Marshaler Envelope
Control the wire format of time and enum fields with MarshalJSON and UnmarshalJSON so the API contract stays stable across refactorings.
Code
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type Status string
const (
StatusActive Status = "active"
StatusArchived Status = "archived"
)
type Task struct {
Title string
Status Status
CreatedAt time.Time
}
func (t Task) MarshalJSON() ([]byte, error) {
// 用别名结构体避免 MarshalJSON 递归调用自身
type envelope struct {
Title string `json:"title"`
Status string `json:"status"`
CreatedAt string `json:"created_at"` // RFC3339 固定契约
}
return json.Marshal(envelope{
Title: t.Title,
Status: string(t.Status),
CreatedAt: t.CreatedAt.UTC().Format(time.RFC3339),
})
}
func (t *Task) UnmarshalJSON(data []byte) error {
var raw struct {
Title string `json:"title"`
Status string `json:"status"`
CreatedAt string `json:"created_at"`
}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
switch Status(raw.Status) {
case StatusActive, StatusArchived:
t.Status = Status(raw.Status)
default:
return fmt.Errorf("unknown status: %q", raw.Status)
}
created, err := time.Parse(time.RFC3339, raw.CreatedAt)
if err != nil {
return fmt.Errorf("created_at: %w", err)
}
t.Title = strings.TrimSpace(raw.Title)
t.CreatedAt = created
return nil
}
func main() {
task := Task{Title: "ship it", Status: StatusActive, CreatedAt: time.Now()}
encoded, _ := json.Marshal(task)
fmt.Println(string(encoded))
var roundTrip Task
fmt.Println(json.Unmarshal(encoded, &roundTrip), roundTrip.Title, roundTrip.Status)
}How it works
Count the functions MarshalJSON, UnmarshalJSON and main as the entire surface area of JSON Custom Marshaler Envelope.
Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
What to watch for
- Errors are ordinary return values; skipping the
errcheck means using a zero value silently.
Using it
Signature: func (t Task) MarshalJSON() ([]byte, error)
Key statements
return fmt.Errorf("created_at: %w", err)
return fmt.Errorf("unknown status: %q", raw.Status)
return json.Marshal(envelope{
Title: t.Title,
Status: string(t.Status),
CreatedAt: t.CreatedAt.UTC().Format(time.RFC3339),
})
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- How does the code signal failure?
- As returned `error` values — 2 sites in the snippet check `err` before using other results.
- How do you run JSON Custom Marshaler Envelope?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.