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.

GoData Integrity

Code

gosnippet
68 lines
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 err check 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

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.