¿Cómo decirle a Jackson que ignore un campo durante la serialización si su valor es null?


Cómo se puede configurar Jackson para ignorar un valor de campo durante la serialización si el valor de ese campo es null.

Por ejemplo:

public class SomeClass {
   // what jackson annotation causes jackson to skip over this value if it is null but will 
   // serialize it otherwise 
   private String someValue; 
}
 564
Author: 0m3r, 2012-08-01

15 answers

Para suprimir propiedades de serialización con valores nulos usando Jackson >2.0, puede configurar el ObjectMapper directamente, o hacer uso del @JsonInclude anotación:

mapper.setSerializationInclusion(Include.NON_NULL);

O:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

Alternativamente, puede usar @JsonInclude en un getter para que el atributo se muestre si el valor no es null.

Un ejemplo más completo está disponible en mi respuesta a Cómo evitar que se obtengan valores nulos dentro de un mapa y campos nulos dentro de un bean serializado a través de Jackson .

 927
Author: Programmer Bruce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-01 16:40:38

Con Jackson > 1.9.11 y @JsonSerialize anotación para hacer eso:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

 115
Author: WTK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-05 08:30:35

Solo para ampliar las otras respuestas: si necesita controlar la omisión de valores nulos por campo, anote el campo en cuestión (o alternativamente anote el 'getter'del campo).

Ejemplo - aquí solo se enviará fieldOne desde json si es null. fieldTwo siempre se incluirá independientemente de si es null.

public class Foo {

    @JsonInclude(JsonInclude.Include.NON_NULL) 
    private String fieldOne;

    private String fieldTwo;
}

Para omitir todos los valores null en la clase como valor predeterminado, anote la clase. Las anotaciones por campo / getter todavía se pueden usar para anular este valor predeterminado si es necesario.

Ejemplo - aquí fieldOne y fieldTwo se omitirán desde json si son null, respectivamente, porque este es el valor predeterminado establecido por la anotación de clase. fieldThree sin embargo, anulará el valor predeterminado y siempre se incluirá, debido a la anotación en el campo.

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Foo {

    private String fieldOne;

    private String fieldTwo;

    @JsonInclude(JsonInclude.Include.ALWAYS)
    private String fieldThree;
}

UPDATE

Lo anterior es para Jackson 2. Para versiones anteriores de Jackson es necesario utilizar:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) 

En su lugar de

@JsonInclude(JsonInclude.Include.NON_NULL)

Si esta actualización es útil, por favor vote la respuesta de ZiglioUK a continuación, señaló la nueva anotación de Jackson 2 mucho antes de actualizar mi respuesta para usarla!

 99
Author: davnicwil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-19 09:18:41

En Jackson 2.x, uso:

@JsonInclude(JsonInclude.Include.NON_NULL)
 55
Author: ZiglioUK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-30 04:24:31

Puede usar la siguiente configuración del mapeador:

mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);

Desde 2.5 puedes usar:

mapper.setSerializationInclusion(Include.NON_NULL);
 29
Author: Eren Yilmaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-26 23:23:20

En mi caso

@JsonInclude(Include.NON_EMPTY)

Hizo que funcionara.

 10
Author: alfthan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-24 19:07:07

Puedes establecer application.properties:

spring.jackson.default-property-inclusion=non_null

O application.yaml:

spring:
  jackson:
    default-property-inclusion: non_null

Http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

 9
Author: Yury,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-05 22:07:55
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_EMPTY)

Debería funcionar.

Include.NON_EMPTY indica que la propiedad está serializada si su valor no es null ni vacío. Include.NON_NULL indica que la propiedad es serializada si su valor no es null.

 6
Author: Neha Gangwar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-02 15:44:15

Si desea agregar esta regla a todos los modelos en Jackson 2.6+ use:

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
 5
Author: Ilia Kurtov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-27 21:52:09

Si está en Spring Boot, puede personalizar el jackson ObjectMapper directamente a través de archivos de propiedades.

Ejemplo application.yml:

spring:
  jackson:
    default-property-inclusion: non_null # only include props if non-null

Los valores posibles son:

always|non_null|non_absent|non_default|non_empty

Más: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper

 4
Author: acdcjunior,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-28 20:56:03

Para Jackson 2.5 utilizar:

@JsonInclude(content=Include.NON_NULL)
 2
Author: Bilal BBB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-19 21:14:05

Esto me ha estado preocupando durante bastante tiempo y finalmente encontré el problema. El problema se debió a una importación incorrecta. Anteriormente había estado usando

com.fasterxml.jackson.databind.annotation.JsonSerialize

Que había sido obsoleto. Simplemente reemplace la importación por

import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

Y utilizarlo como

@JsonSerialize(include=Inclusion.NON_NULL)
 1
Author: user3443646,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-24 07:13:37

Si estás tratando de serializar una lista de objetos y uno de ellos es null, terminarás incluyendo el elemento null en el json incluso con

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

Resultará en:

[{myObject}, null]

Para obtener esto:

[{miObjeto}]

Uno puede hacer algo como:

mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
        @Override
        public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused)
                throws IOException
        {
            //IGNORES NULL VALUES!
        }
    });

CONSEJO: Si está utilizando DropWizard, puede recuperar el ObjectMapper que está utilizando Jersey utilizando environment.getObjectMapper ()

 1
Author: user3474985,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-23 06:42:35

Configuración global si utiliza Spring

@Configuration
public class JsonConfigurations {

    @Bean
    public Jackson2ObjectMapperBuilder objectMapperBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
        builder.failOnUnknownProperties(false);
        return builder;
    }

}
 1
Author: Xelian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-22 20:57:34

Jackson 2.x + use

mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.NON_NULL);
 0
Author: mekdev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-16 16:02:27