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.
Code
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
JSON Pointer EvaluatorEvaluate RFC 6901 JSON Pointer strings against a JSON document to extract the referenced value, with tilde-slash escape handling.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.