Override JSON serialization of golang type struct

by Gregor Uhlenheuer on October 9, 2019

In Golang you sometimes want to modify or extend the (JSON) serialization of a type that you cannot modify itself (e.g. part of an external library) or maybe you want to serialize the same type in different kinds.

Usually however you define the type of serialization via type tags as part of the struct declaration.

Anonymous type

You can get around this fact by facilitating an anonymous type and embed your target type as part of it. A quick example might look like this:

Example

For demonstration sake the example above might look like the following:

The shown practice is not specific to JSON serialization at all - it can be used for other tag based values as well of course.

This post is tagged with programming and golang