← 中文资源

简体中文版本

JSON 自定义 Marshaler 契约

用 MarshalJSON/UnmarshalJSON 固定线上格式:时间统一 RFC3339、枚举白名单校验、别名结构体避免递归。

阅读英文原文

实现说明

除了函数 MarshalJSON、UnmarshalJSON、main,文件里再无其他定义。 错误处理是内联的:2 处测试 err != nil 并立即分支。

使用要点

  • 没有可捕获的异常——每个调用点都必须检查 err 返回值。

常见问题

代码如何报告失败?

以返回的 error 值上报——示例里 2 处在使用其他结果前先检查 err。

「JSON 自定义 Marshaler 契约」这个示例怎么运行?

运行这个文件就行;脚本没有任何外部要求。

主签名形如 func (t Task) MarshalJSON() ([]byte, error)

核心语句

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),
})

代码示例

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)
}