programing tip

값이 null 인 경우 직렬화 중에 Jackson에게 필드를 무시하도록 지시하는 방법은 무엇입니까?

itbloger 2020. 10. 2. 21:48
반응형

값이 null 인 경우 직렬화 중에 Jackson에게 필드를 무시하도록 지시하는 방법은 무엇입니까?


필드 값이 null 인 경우 직렬화 중에 필드 값을 무시하도록 Jackson을 구성하려면 어떻게해야합니까?

예를 들면 :

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; 
}

Jackson> 2.0을 사용하여 null 값으로 속성을 직렬화하지 않으려면 직접 구성ObjectMapper 하거나 @JsonInclude주석 을 사용할 수 있습니다 .

mapper.setSerializationInclusion(Include.NON_NULL);

또는:

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

또는 @JsonInclude값이 null이 아닌 경우 속성이 표시되도록 getter에서 사용할 수 있습니다 .

더 완벽한 예에서 볼 수 있습니다 내 대답잭슨을 통해 직렬화하기에서 빈 내부지도 내부 널 (null) 값과 널 (null) 필드를 방지하는 방법 .


Jackson> 1.9.11 및 <2.x에서는 @JsonSerialize주석을 사용 하여 다음을 수행합니다.

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)


다른 답변을 확장하기 위해-필드별로 null 값의 생략을 제어해야하는 경우 해당 필드에 주석을 달거나 필드의 'getter'에 주석을 추가합니다.

예- 여기서는 fieldOnenull 인 경우 에만 json에서 생략됩니다. fieldTwonull 여부에 관계없이 항상 포함됩니다.

public class Foo {

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

    private String fieldTwo;
}

클래스의 모든 null 값을 기본값으로 생략하려면 클래스에 주석을 추가하십시오. 필요한 경우 필드 / 게터 별 주석을 사용하여이 기본값을 재정의 할 수 있습니다.

예 - 여기 fieldOnefieldTwo그들이 각각 null의 경우이 클래스 주석하여 기본 설정이기 때문에, JSON에서 ommitted됩니다. fieldThree그러나 필드의 주석 때문에 기본값이 무시되고 항상 포함됩니다.

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

    private String fieldOne;

    private String fieldTwo;

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

최신 정보

The above is for Jackson 2. For earlier versions of Jackson you need to use:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) 

instead of

@JsonInclude(JsonInclude.Include.NON_NULL)

If this update is useful, please upvote ZiglioUK's answer below, it pointed out the newer Jackson 2 annotation long before I updated my answer to use it!


In Jackson 2.x, use:

@JsonInclude(JsonInclude.Include.NON_NULL)

You can use the following mapper configuration:

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

Since 2.5 you can user:

mapper.setSerializationInclusion(Include.NON_NULL);

You can set application.properties:

spring.jackson.default-property-inclusion=non_null

or application.yaml:

spring:
  jackson:
    default-property-inclusion: non_null

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


in my case

@JsonInclude(Include.NON_EMPTY)

made it work.


@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_EMPTY)

should work.

Include.NON_EMPTY indicates that property is serialized if its value is not null and not empty. Include.NON_NULL indicates that property is serialized if its value is not null.


If you want to add this rule to all models in Jackson 2.6+ use:

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

If in Spring Boot, you can customize the jackson ObjectMapper directly through property files.

Example application.yml:

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

Possible values are:

always|non_null|non_absent|non_default|non_empty

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


This Will work in Spring boot 2.0.3+ and Jackson 2.0+

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiDTO
{
    // your class variable and 
    // methods
}

For Jackson 2.5 use :

@JsonInclude(content=Include.NON_NULL)

This has been troubling me for quite some time and I finally found the issue. The issue was due to a wrong import. Earlier I had been using

com.fasterxml.jackson.databind.annotation.JsonSerialize

Which had been deprecated. Just replace the import by

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

and use it as

@JsonSerialize(include=Inclusion.NON_NULL)

Global configuration if you use 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;
    }

}

If you're trying to serialize a list of object and one of them is null you'll end up including the null item in the JSON even with

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

will result in:

[{myObject},null]

to get this:

[{myObject}]

one can do something like:

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

TIP: If you're using DropWizard you can retrieve the ObjectMapper being used by Jersey using environment.getObjectMapper()


Jackson 2.x+ use

mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.NON_NULL);

Also, you have to change your approach when using Map myVariable as described in the documentation to eleminate nulls:

From documentation:
com.fasterxml.jackson.annotation.JsonInclude

@JacksonAnnotation
@Target(value={ANNOTATION_TYPE, FIELD, METHOD, PARAMETER, TYPE})
@Retention(value=RUNTIME)
Annotation used to indicate when value of the annotated property (when used for a field, method or constructor parameter), or all properties of the annotated class, is to be serialized. Without annotation property values are always included, but by using this annotation one can specify simple exclusion rules to reduce amount of properties to write out.

*Note that the main inclusion criteria (one annotated with value) is checked on Java object level, for the annotated type, and NOT on JSON output -- so even with Include.NON_NULL it is possible that JSON null values are output, if object reference in question is not `null`. An example is java.util.concurrent.atomic.AtomicReference instance constructed to reference null value: such a value would be serialized as JSON null, and not filtered out.

To base inclusion on value of contained value(s), you will typically also need to specify content() annotation; for example, specifying only value as Include.NON_EMPTY for a {link java.util.Map} would exclude Maps with no values, but would include Maps with `null` values. To exclude Map with only `null` value, you would use both annotations like so:
public class Bean {
   @JsonInclude(value=Include.NON_EMPTY, content=Include.NON_NULL)
   public Map<String,String> entries;
}

Similarly you could Maps that only contain "empty" elements, or "non-default" values (see Include.NON_EMPTY and Include.NON_DEFAULT for more details).
In addition to `Map`s, `content` concept is also supported for referential types (like java.util.concurrent.atomic.AtomicReference). Note that `content` is NOT currently (as of Jackson 2.9) supported for arrays or java.util.Collections, but supported may be added in future versions.
Since:
2.0

참고URL : https://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null

반응형