[go] encoding/json/v2: add MarshalerTo and UnmarshalerFrom examples

0 views
Skip to first unread message

Michael Pratt (Gerrit)

unread,
Aug 6, 2026, 2:54:18 PM (4 days ago) Aug 6
to Michael Pratt, goph...@pubsubhelper.golang.org, golang-...@googlegroups.com, golang...@luci-project-accounts.iam.gserviceaccount.com, Jonathan Amsterdam, Joseph Tsai, Damien Neil, golang-co...@googlegroups.com

Michael Pratt submitted the change with unreviewed changes

Unreviewed changes

5 is the latest approved patch-set.
The change was submitted with unreviewed changes in the following files:

```
The name of the file: src/encoding/json/v2/example_marshaljson_test.go
Insertions: 5, Deletions: 6.

@@ -36,12 +36,11 @@
}

for k := range keys {
- // It's tempting to to just call
- // enc.WriteValue(jsontext.Int(k)) here, since we have a
- // number. Unfortunately that would ignore a global
- // json.StringifyNumbers option. Going through MarshalEncode is
- // the safe option, as it ensure we get all of the standard
- // marshal behavior for the key type.
+ // Call MarshalEncode instead of Write methods on Encoder so
+ // that the "json" package can automatically handle any options
+ // that may be relevant to the representation of k.
+ // In this case, StringifyNumbers may affect whether k is
+ // quoted or not.
if err := json.MarshalEncode(enc, k); err != nil {
return err
}
```

Change information

Commit message:
encoding/json/v2: add MarshalerTo and UnmarshalerFrom examples

MarshalerTo and UnmarshalerFrom are the preferred way to implement
custom marshaling, but don't have any attached examples.

Add examples for a straightforward set type. I like this example because
it is fairly simple, but also encourages users to handle options.

I continue to be undecided about whether a custom type like this should
want to adhere to StringifyNumbers.

For #71497.
Change-Id: Ib8b92b58cb11cfc47ed5537b2d0740a96a6a6964
Reviewed-by: Jonathan Amsterdam <j...@google.com>
Files:
  • A src/encoding/json/v2/example_marshaljson_test.go
Change size: M
Delta: 1 file changed, 126 insertions(+), 0 deletions(-)
Branch: refs/heads/master
Submit Requirements:
Open in Gerrit
Inspect html for hidden footers to help with email filtering. To unsubscribe visit settings. DiffyGerrit
Gerrit-MessageType: merged
Gerrit-Project: go
Gerrit-Branch: master
Gerrit-Change-Id: Ib8b92b58cb11cfc47ed5537b2d0740a96a6a6964
Gerrit-Change-Number: 810321
Gerrit-PatchSet: 8
Gerrit-Owner: Michael Pratt <mpr...@google.com>
Gerrit-Reviewer: Damien Neil <dn...@google.com>
Gerrit-Reviewer: Jonathan Amsterdam <j...@google.com>
Gerrit-Reviewer: Joseph Tsai <joe...@digital-static.net>
Gerrit-Reviewer: Michael Pratt <mpr...@google.com>
open
diffy
satisfied_requirement
Reply all
Reply to author
Forward
0 new messages