MarshalJSON On Pointer Receiver

MarshalJSON on a pointer receiver is skipped when marshaling the bare value, so the JSON falls back to reflection; pass the pointer to engage it.

GoData Integrity

Code

gosnippet
29 lines
package main

import (
	"encoding/json"
	"fmt"
)

type Task struct {
	ID   int
	Note string
}

// MarshalJSON 定义在指针接收者上:只有 *Task 满足 json.Marshaler 接口
func (t *Task) MarshalJSON() ([]byte, error) {
	payload := map[string]any{"id": t.ID, "note": t.Note}
	return json.Marshal(payload)
}

func main() {
	task := Task{ID: 7, Note: "alpha"}

	// 传值:Task 的方法集不含指针接收者方法 → 退回反射默认输出
	byValue, _ := json.Marshal(task)
	fmt.Println("value :", string(byValue))

	// 传指针:自定义编码生效
	byPointer, _ := json.Marshal(&task)
	fmt.Println("pointer:", string(byPointer))
}

Inside the snippet

Structurally, expect the functions MarshalJSON and main and nothing else.

Caveats

  • Entirely standard-library — copy it in and it runs.

Putting it to use

Entry signature: func (t *Task) MarshalJSON() ([]byte, error)

Output lines are prefixed (value :, pointer:), so the effect of every step stays on display.

Load-bearing lines

func (t *Task) MarshalJSON() ([]byte, error) {
	payload := map[string]any{"id": t.ID, "note": t.Note}
	return json.Marshal(payload)
}
func main() {
	task := Task{ID: 7, Note: "alpha"}
	// 传值:Task 的方法集不含指针接收者方法 → 退回反射默认输出
	byValue, _ := json.Marshal(task)
	fmt.Println("value :", string(byValue))
	// 传指针:自定义编码生效
	byPointer, _ := json.Marshal(&task)
	fmt.Println("pointer:", string(byPointer))
}

Interactive Tools for This Topic

FAQ

What does MarshalJSON On Pointer Receiver print when run?
Run it as a complete program — the output lines carry labels such as `value :`, `pointer:`.