jackson-databind
jackson-databind copied to clipboard
UsingJsonInclude.Include.NON_DEFAULT together with JsonTypeInfo.defaultImpl should exclude the type property.
Is your feature request related to a problem? Please describe.
I'm trying to serialize a minimized Dropwizard configuration object, excluding any default values, in https://github.com/motlin/liftwizard/pull/2011/files.
The first thing I tried was setting Include.NON_DEFAULT globally, but it's well documented on the annotation itself that it does not work on objects globally, only primitives.
ObjectMapper nonDefaultObjectMapper = objectMapper.copy();
nonDefaultObjectMapper.setDefaultPropertyInclusion(Include.NON_DEFAULT);
nonDefaultObjectMapper.setSerializationInclusion(Include.NON_DEFAULT);
I came up with a decent workaround using mixins.
@JsonInclude(Include.NON_DEFAULT)
public class JsonIncludeNonDefaultMixIn
{
}
public class JsonIncludeNonDefaultMixInResolver
implements MixInResolver
{
@Override
public Class<?> findMixInClassFor(Class<?> cls)
{
return JsonIncludeNonDefaultMixIn.class;
}
@Override
public MixInResolver copy()
{
return this;
}
}
ObjectMapper nonDefaultObjectMapper = objectMapper.copy();
nonDefaultObjectMapper.setMixInResolver(new JsonIncludeNonDefaultMixInResolver());
String configurationString = nonDefaultObjectMapper.writeValueAsString(configuration);
LOGGER.info("Dropwizard configuration (minimized):\n{}", configurationString);
This works fairly well and excludes most default values. Now when serializing a default configuration object, most of the remaining content comes from default type information set using JsonTypeInfo. For example:
"logging": {
"type": "default",
"appenders": [
{
"type": "console"
}
]
},
Describe the solution you'd like
I'd like some way of excluding as many json fields as possible that get serialized on an object created with its default constructor, specifically the default type information from JsonTypeInfo's defaultImpl
Usage example
@JsonInclude(Include.NON_DEFAULT)
@JsonTypeInfo(use = Id.NAME, property = "type", defaultImpl = ExampleClass.class)
public interface ExampleInterface
{
}
@JsonTypeName("default")
@JsonInclude(Include.NON_DEFAULT)
public static class ExampleClass implements ExampleInterface
{
}
ExampleClass exampleClass = new ExampleClass();
String string = objectMapper.writeValueAsString(exampleClass);
String is:
{
"type": "default"
}
I'd expect the empty object {} here.
Additional context
No response