New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/json: allow override type marshaling #5901

Open
rsc opened this Issue Jul 17, 2013 · 6 comments

Comments

Projects
None yet
4 participants
@rsc
Contributor

rsc commented Jul 17, 2013

For example, if a user wants to marshal net.IP with custom code, we should provide a way
to do that, probably a method on *Encoder. Similarly for *Decoder.

Same for encoding/xml.
@robpike

This comment has been minimized.

Contributor

robpike commented Aug 20, 2013

Comment 1:

Labels changed: removed go1.3.

@rsc

This comment has been minimized.

Contributor

rsc commented Nov 27, 2013

Comment 2:

Labels changed: added go1.3maybe.

@rsc

This comment has been minimized.

Contributor

rsc commented Dec 4, 2013

Comment 3:

Labels changed: added release-none, removed go1.3maybe.

@rsc

This comment has been minimized.

Contributor

rsc commented Dec 4, 2013

Comment 4:

Labels changed: added repo-main.

@rsc rsc added accepted labels Dec 4, 2013

@rsc rsc added this to the Unplanned milestone Apr 10, 2015

@odeke-em

This comment has been minimized.

Member

odeke-em commented Jan 2, 2017

I did some work on this sometime back in October, with CL https://go-review.googlesource.com/c/31091 to get the conversation started.
Perhaps we can work on it for Go1.9.

In there I introduced Encoder.RegisterEncoder

func (enc *Encoder) RegisterEncoder(t reflect.Type, fn func(interface{}) ([]byte, error))

and Decoder.RegisterDecoder

func (dec *Decoder) RegisterDecoder(t reflect.Type, fn func([]byte) (interface{}, error))
@sebastien-rosset

This comment has been minimized.

sebastien-rosset commented Sep 14, 2017

We have a similar requirement for custom serialization. Our specific use cases are:

  1. Data anonymization. For example, omit IP addresses in the JSON output.
  2. Data masking. For example, omit specific fields depending on user privileges.
  3. Omit empty values (e.g. empty strings). This is useful to generate compact documents.
    In all three cases, the decision to omit fields is done at runtime with contextual information.

We are using CiscoM31@1e9514f. In our case, the client interface is implemented by doing a simple lookup in a map, so there is no need to register hundreds of custom marshaller (we have lots of structs).
We could have used a technique similar to https://go-review.googlesource.com/c/31091.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment