← 中文资源

简体中文版本

TextMarshaler 自定义 JSON 键

给自定义键类型实现 encoding.TextMarshaler/TextUnmarshaler,让 map 的整数键编码成 acct-0007 这类字符串,并能反解回原类型。

阅读英文原文

实现说明

真正干活的是函数 MarshalText、UnmarshalText、main,其余都是接线。 没有静默穿透——中途有 3 个检查点测试 err != nil。

使用要点

  • 这里没有 panic 路径——失败以 error 值返回,每个调用方都得处理。
  • 演示输出是带标签的(encode failed:、decode failed:、account 7:),每个操作都会留下自己的一行标注。

常见问题

有异常处理吗?

通过 error 值而非 panic——示例在 3 处检查 err != nil。

运行「TextMarshaler 自定义 JSON 键」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 encode failed:、decode failed:、account 7: 标签标明各步骤。

主要签名是 func (id AccountID) MarshalText() ([]byte, error)

核心语句

return fmt.Errorf("account key %q: %w", text, err)
return fmt.Errorf("account key %q lacks acct- prefix", text)
return []byte(fmt.Sprintf("acct-%04d", int(id))), nil

代码示例

package main

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
)

type AccountID int

// encoding.TextMarshaler supplies JSON object keys, which must encode as strings
func (id AccountID) MarshalText() ([]byte, error) {
	return []byte(fmt.Sprintf("acct-%04d", int(id))), nil
}

func (id *AccountID) UnmarshalText(text []byte) error {
	raw, ok := strings.CutPrefix(string(text), "acct-")
	if !ok {
		return fmt.Errorf("account key %q lacks acct- prefix", text)
	}
	value, err := strconv.Atoi(raw)
	if err != nil {
		return fmt.Errorf("account key %q: %w", text, err)
	}
	*id = AccountID(value)
	return nil
}

func main() {
	balances := map[AccountID]int{7: 120, 42: 30, 315: 8}

	encoded, err := json.Marshal(balances)
	if err != nil {
		fmt.Println("encode failed:", err)
		return
	}
	fmt.Println(string(encoded)) // 键由 MarshalText 决定

	var decoded map[AccountID]int
	if err := json.Unmarshal(encoded, &decoded); err != nil {
		fmt.Println("decode failed:", err)
		return
	}
	fmt.Println("account 7:", decoded[7])
	fmt.Println("account 315:", decoded[315])
}