FasterXML / FasterXML/jackson-databind
Using `JsonInclude.Include.NON_DEFAULT` together with `JsonTypeInfo.defaultImpl` should exclude the type property
- Dominant language
- Java
- Stars
- 3.7k
- Forks
- 1.5k
- Avg merge
- 3d 6h
- Merged PRs (30d)
- 28
Description
### 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](https://github.com/FasterXML/jackson-annotations/blob/jackson-annotations-2.17.1/src/main/java/com/fasterxml/jackson/annotation/JsonInclude.java#L189-L210) that it does not work on objects globally, only primitives.
```java
ObjectMapper nonDefaultObjectMapper = objectMapper.copy();
nonDefaultObjectMapper.setDefaultPropertyInclusion(Include.NON_DEFAULT);
nonDefaultObjectMapper.setSerializationInclusion(Include.NON_DEFAULT);
```
I came up with a decent workaround using mixins.
```java
@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:
```json5
"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
```java
@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:
```json
{
"type": "default"
}
```
I'd expect the empty object `{}` here.
### Additional context
_No response_
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.