programing

값이 null인 경우 직렬화 중에 필드를 무시하도록 잭슨에게 지시하려면 어떻게 해야 합니까?

itsource 2022. 8. 2. 23:59
반응형

값이 null인 경우 직렬화 중에 필드를 무시하도록 잭슨에게 지시하려면 어떻게 해야 합니까?

직렬화 중에 필드 값이 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; 
}

잭슨 > 2.0을 사용하여 늘 값을 사용하여 속성을 시리얼화하지 않도록 하려면 를 직접 설정하거나 주석을 사용합니다.

mapper.setSerializationInclusion(Include.NON_NULL);

또는 다음과 같이 입력합니다.

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

'보다 낫다'를 사용할 도 있습니다.@JsonInclude【null】【Attribute】【아트리뷰트】【getter】【getter】.

자세한 예는 "맵 내의 늘 값과 의 늘 필드가 잭슨을 통해 시리얼화되지 않도록 하는 방법"에 대한 답변에서 확인할 수 있습니다.

다른 답변에 대해 자세히 설명하겠습니다. 필드 단위로 null 값의 누락 여부를 제어해야 할 경우 해당 필드에 주석을 달거나 필드의 'getter'에 주석을 달 수 있습니다.

예 - 여기만fieldOnenull JSON이 됩니다. fieldTwoJSON을 사용하다

public class Foo {

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

    private String fieldTwo;
}

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

예 - 여기fieldOne ★★★★★★★★★★★★★★★★★」fieldTwo는 클래스 주석에서 기본 설정이기 때문에 각각 null인 경우 JSON에서 생략됩니다. fieldThree그러나 필드의 주석으로 인해 기본값이 재정의되고 항상 포함됩니다.

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

    private String fieldOne;

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

갱신하다

위는 Jackson 2를 위한 것입니다.Jackson의 이전 버전에서는 다음을 사용해야 합니다.

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) 

대신

@JsonInclude(JsonInclude.Include.NON_NULL)

이 업데이트가 도움이 된다면 Ziglio를 투표해 주십시오.아래 UK의 답변은 내가 사용하기 위해 답변을 업데이트하기 훨씬 전에 새로운 Jackson 2 주석을 지적한 것입니다.

Jackson < 2x > 1.9.11 의 경우는,< 2.x > 를 합니다.@JsonSerialize주석을 사용하여 다음을 수행합니다.

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

Jackson 2.x에서는 다음을 사용합니다.

@JsonInclude(JsonInclude.Include.NON_NULL)

다음 매퍼 설정을 사용할 수 있습니다.

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

2.5 이후로는, 다음의 기능을 사용할 수 있습니다.

mapper.setSerializationInclusion(Include.NON_NULL);

설정할 수 .application.properties:

spring.jackson.default-property-inclusion=non_null

★★★★★★★★★★★★★★★★★」application.yaml:

spring:
  jackson:
    default-property-inclusion: non_null

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

나 같은 경우에는

@JsonInclude(Include.NON_EMPTY)

성공했어요.

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

작동해야 합니다.

Include.NON_EMPTY값은 늘이 아니고 비어 있지 않은 경우 속성이 시리얼화됨을 나타냅니다. Include.NON_NULL값이 늘이 아닌 경우 속성이 시리얼화됨을 나타냅니다.

이것은 스프링 부트 2.0.3+ 잭슨 2.0+에서 동작합니다.

import com.fasterxml.jackson.annotation.JsonInclude;

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

잭슨 2.6 이상의 모든 모델에 이 규칙을 추가하려면 다음을 사용합니다.

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

Spring Boot에서 잭슨은 커스터마이즈할수있습니다.ObjectMapper속성 파일을 통해 직접 확인할 수 있습니다.

application.yml:

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

사용 가능한 값은 다음과 같습니다.

always|non_null|non_absent|non_default|non_empty

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

잭슨 2.5의 경우:

@JsonInclude(content=Include.NON_NULL)

오브젝트 목록을 시리얼화하려고 하는데 그 중 하나가 null일 경우 null 항목이 JSON에 포함됩니다.

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

결과는 다음과 같습니다.

[{myObject},null]

입수 방법:

[{myObject}]

다음과 같은 작업을 수행할 수 있습니다.

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

팁: DropWizard를 사용하고 있다면ObjectMapperJersey가 사용하는 것environment.getObjectMapper()

이것은 꽤 오랫동안 나를 괴롭혔고 나는 마침내 문제를 발견했다.이 문제는 잘못된 수입으로 인한 것입니다.아까부터 쓰고 있었어요.

com.fasterxml.jackson.databind.annotation.JsonSerialize

더 이상 권장되지 않았던 것.Import를 다음으로 바꿉니다.

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

그리고 그것을 로서

@JsonSerialize(include=Inclusion.NON_NULL)

스프링을 사용하는 경우 글로벌 구성

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

}

우리는 이 질문에 대한 많은 답을 가지고 있다.이 답변은 경우에 따라 도움이 될 수 있습니다.null 값을 무시하려면 다음과 같이 클래스 수준에서 NOT_NULL을 사용할 수 있습니다.

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

arrayList를 초기화했지만 목록에 요소가 없는 경우와 같이 빈 값을 무시해야 하는 경우가 있습니다.이 때 NOT_EMPTY 주석을 사용하여 빈 값 필드를 무시합니다.

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

케이스 1

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

케이스 2

@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String someString;

한다면someStringnull 이므로 두 경우 모두 무시됩니다.한다면someString"는 것은 단지 케이스 2에서만 무시됩니다.

에 대해서도 마찬가지입니다.List = null또는List.size() = 0

Jackson 2.x+ 사용

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

또한 매뉴얼에 설명되어 있는 Map myVariable을 사용할 때는 늘을 생성하도록 접근 방식을 변경해야 합니다.

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

시험해 보세요-

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class XYZ {
    
    protected String field1;
    
    protected String field2;
 }

null이 아닌 값의 경우(getters/class 수준에서) -

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)

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

반응형