Don't return property when it's an empty list with jackson

You can use @JsonInclude(JsonInclude.Include.NON_EMPTY) annotation on your class or filed.

import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
class Person
{
    String name;
    List<Event> events;
    //....getter, setter
}

If you can change your original model with Jackson annotations, here is the way how to achieve this.

Jackson has WRITE_EMPTY_JSON_ARRAYS. And you may turn off it with:

objectMapper.configure(SerializationConfig.Feature.WRITE_EMPTY_JSON_ARRAYS, false);

But it works only for Arrays, but not for Collections. But you may combine @JsonProperty with @JsonIgnore, something like the following:

//....getter, setter of Person class
@JsonIgnore
public List<Event> getEvents() {
    return events;
}

@JsonProperty("events")
public Event[] getEventsArr() {
    return events.toArray(new Event[0]);
}

And afterwards you'll have output, as you expected.

EDIT: If you are using SpringMVC, then you can configure your actual ObjectMapper with explicit reference in mvc:annotation-driven:

<!-- Configures the @Controller programming model -->
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="objectMapper" ref="objectMapper"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

<!--custom Json Mapper configuration-->
<bean name="objectMapper" class="org.springframework.http.converter.json.JacksonObjectMapperFactoryBean" autowire="no">
    <property name="featuresToDisable">
        <list>
            <!--Ignore unknown properties-->
            <value type="org.codehaus.jackson.map.SerializationConfig.Feature">WRITE_EMPTY_JSON_ARRAYS</value>
        </list>
    </property>
</bean>

Offtop: usually it's quite useful to specify explicit instance of ObjectMapper, because:

  • you can configure it in the way you want
  • you can use its reference through @Autowired

If you are using Spring Boot, just add in your application.properties the following :

spring.jackson.serialization-inclusion=NON_EMPTY

Tags:

Java

Json

Jackson