Alias Trick Extends UnmarshalJSON

Extend json decoding without recursion: an alias type keeps the default decode while UnmarshalJSON normalizes fields on the way in.

GoConfig Management

Code

gosnippet
58 lines
package main

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

// Config 在解码期做归一化:retries 既接受 3 也接受 "3"
type Config struct {
	Retries int    `json:"retries"`
	Mode    string `json:"mode"`
}

// UnmarshalJSON 直接 Unmarshal 进自己会无限递归
func (c *Config) UnmarshalJSON(data []byte) error {
	// alias 类型没有方法:先按默认规则解码
	type configAlias Config
	var raw struct {
		configAlias
		Retries json.RawMessage `json:"retries"` // 覆盖提升字段,留住原始字节
	}
	if err := json.Unmarshal(data, &raw); err != nil {
		return err
	}

	var n int
	if err := json.Unmarshal(raw.Retries, &n); err == nil {
		raw.configAlias.Retries = n
	} else {
		var s string
		if err := json.Unmarshal(raw.Retries, &s); err != nil {
			return fmt.Errorf("retries: want int or string, got %s", raw.Retries)
		}
		parsed, err := strconv.Atoi(s)
		if err != nil {
			return fmt.Errorf("retries %q: not a number", s)
		}
		raw.configAlias.Retries = parsed
	}
	*c = Config(raw.configAlias)
	return nil
}

func main() {
	for _, payload := range []string{
		`{"retries": 3, "mode": "fast"}`,
		`{"retries": "5", "mode": "safe"}`,
		`{"retries": "abc", "mode": "safe"}`,
	} {
		var cfg Config
		if err := json.Unmarshal([]byte(payload), &cfg); err != nil {
			fmt.Println("rejected:", err)
			continue
		}
		fmt.Printf("ok: retries=%d mode=%s\n", cfg.Retries, cfg.Mode)
	}
}

The structure at work

Alias Trick Extends UnmarshalJSON is built around the functions UnmarshalJSON and main.

The cycling part of this snippet is for _, payload := range []string. Every fallible call checks err != nil (4 sites), so an error is handled where it happens rather than bubbling invisibly.

Watch out for

  • The function reports failure by returning error — callers branch on it before touching other results.

Applying it

Entry signature: func (c *Config) UnmarshalJSON(data []byte) error

Output lines are prefixed (rejected:, ok: retries=), so the source of each printed line stays identifiable.

Statements that matter

return fmt.Errorf("retries: want int or string, got %s", raw.Retries)
return fmt.Errorf("retries %q: not a number", s)

Interactive Tools for This Topic

FAQ

What is the error handling style?
By return value: each fallible call hands back an `error`, checked at 4 places here.
What does Alias Trick Extends UnmarshalJSON print when run?
Running the file directly is enough — expect labeled output lines such as `rejected:`, `ok: retries=`.