encoding/json: clarify that v1 Marshal calls MarshalerTo methods

v1 is implemented in terms of v2, and as such inherits support for
MarshalerTo. This is important to ensure that types implementing
MarshalerTo are usable by all clients, not just v2 clients.

Update the v1 Marshal docs to add MarshalerTo to the precedence rules.
I've reused the nice bulleted formatting used in v2.

For #71497.

Change-Id: Ifc0e89ce7203aa51016c1056ebaf69ac6a6a6964
Reviewed-on: https://go-review.googlesource.com/c/go/+/775180
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
Michael Pratt 2026-05-07 10:20:32 -04:00
parent a40c232e81
commit b9c5520dbc

View file

@ -30,14 +30,24 @@ import (
// Marshal returns the JSON encoding of v.
//
// Marshal traverses the value v recursively.
// If an encountered value implements [Marshaler]
// and is not a nil pointer, Marshal calls [Marshaler.MarshalJSON]
// to produce JSON. If no [Marshaler.MarshalJSON] method is present but the
// value implements [encoding.TextMarshaler] instead, Marshal calls
// [encoding.TextMarshaler.MarshalText] and encodes the result as a JSON string.
// The nil pointer exception is not strictly necessary
// but mimics a similar, necessary exception in the behavior of
// [Unmarshaler.UnmarshalJSON].
//
// The input value is encoded as JSON according the following rules:
//
// - If the value type implements [encoding/json/v2.MarshalerTo],
// then the MarshalJSONTo method is called to encode the value.
// If the method returns [errors.ErrUnsupported],
// then the input is encoded according to subsequent rules.
//
// - If the value type implements [Marshaler],
// then the MarshalJSON method is called to encode the value.
//
// - If the value type implements [encoding.TextAppender],
// then the AppendText method is called to encode the value and
// subsequently encode its result as a JSON string.
//
// - If the value type implements [encoding.TextMarshaler],
// then the MarshalText method is called to encode the value and
// subsequently encode its result as a JSON string.
//
// Otherwise, Marshal uses the following type-dependent default encodings:
//