Is it possible to ignore a custom MarshalJSON implementation of a struct,
and use just standard marshaling function instead?
The struct is complex, and has a lot of nested structs, all of which are
using custom MarshalJSON, and I would like to ignore them all.
I feel that it should be trivial. Do you have an idea?
Some details
An obvious solution with a new type creation does not work well, because the nested structs still use their MarshalJSONs.
Here is an example of the code:
func (de DeploymentExtended) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if de.Location != nil {
objectMap["location"] = de.Location
}
if de.Properties != nil {
objectMap["properties"] = de.Properties
}
if de.Tags != nil {
objectMap["tags"] = de.Tags
}
return json.Marshal(objectMap)
}
And there are a lot of properties (like Name, etc), which I would like to see in my JSON (the same for Properties and other nested structs).
The Python implementation of this code provides that data, my software use it, and I (porting the code to Go) would like to be able to export these data from my Go program too.
You can do this two ways:
MarshalJSONmethods); orreflectto ignore anyMarshalJSONmethods at runtime)Custom Types
For example, take these nested types:
one would need to shadow these types to avoid the unwanted
MarshalJSONmethods from being invoked:https://go.dev/play/p/vzKtb0gZZov
Reflection
Here's a simple
reflect-based JSON marshaler to achieve what you want. It assumes that all the custom marshalers use pointer receivers - and dereferences the pointer so the standard library'sjson.Marshalwill not "see" them:YMMV with this method.
https://go.dev/play/p/v9YjYRno7RV