programing

Jackson [duplicate]를 사용하여 JSON 객체의 새 필드 무시

nasanasas 2020. 10. 3. 10:55
반응형

Jackson [duplicate]를 사용하여 JSON 객체의 새 필드 무시


이 질문에 이미 답변이 있습니다.

Jackson JSON 라이브러리를 사용하여 일부 JSON 개체를 Android 응용 프로그램의 POJO 클래스로 변환하고 있습니다. 문제는 애플리케이션이 게시되는 동안 JSON 개체가 변경되고 새 필드가 추가 될 수 있지만 현재는 무시해도되는 간단한 문자열 필드가 추가 되어도 중단됩니다.

Jackson에게 새로 추가 된 필드를 무시하도록 지시하는 방법이 있습니까? (예 : POJO 객체에 존재하지 않음)? 글로벌 무시가 좋을 것입니다.


Jackson은 클래스 수준 ( JsonIgnoreProperties ) 에서 사용할 수있는 주석을 제공합니다 .

(클래스의 상단에 다음을 추가 하지 각각의 방법에) :

@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {
    ...
}

사용중인 jackson 버전에 따라 현재 버전에서 다른 가져 오기를 사용해야합니다.

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

이전 버전에서는 다음과 같습니다.

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

이미 언급 한 두 가지 메커니즘 외에도 알 수없는 (매핑되지 않은) 속성으로 인한 모든 오류를 억제하는 데 사용할 수있는 전역 기능이 있습니다.

// jackson 1.9 and before
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// or jackson 2.0
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

이것은 주석이 없을 때 사용되는 기본값이며 편리한 폴 백이 될 수 있습니다.


Jackson 2에 대한 최신 및 완전한 답변


주석 사용

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyMappingClass {

}

Jackson 온라인 설명서의 JsonIgnoreProperties참조하십시오 .

구성 사용

주석보다 덜 거슬립니다.

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

ObjectReader objectReader = objectMapper.reader(MyMappingClass.class);
MyMappingClass myMappingClass = objectReader.readValue(json);

Jackson 온라인 문서에서 FAIL_ON_UNKNOWN_PROPERTIES참조하십시오 .


두 가지 방법으로 달성 할 수 있습니다.

  1. 알 수없는 속성을 무시하도록 POJO 표시

    @JsonIgnoreProperties(ignoreUnknown = true)
    
  2. Configure ObjectMapper that serializes/De-serializes the POJO/json as below:

    ObjectMapper mapper =new ObjectMapper();            
    // for Jackson version 1.X        
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // for Jackson version 2.X
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) 
    

If using a pojo class based on JSON response. If chances are there that json changes frequently declare at pojo class level:

@JsonIgnoreProperties(ignoreUnknown = true)

and at the objectMapper add this if you are converting:

objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

So that code will not break.


@JsonIgnoreProperties(ignoreUnknown = true) worked well for me. I have a java application which runs on tomcat with jdk 1.7.


Starting with Jackson version 2.4 and above there have been some changes. Here is how you do it now:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

..........................................................................

 ObjectMapper mapper = new ObjectMapper();
    // to prevent exception when encountering unknown property:
 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

Note: The @annotation based solution remains the same so if you like to use that see the other answers.

For more information see the 10 minutes Configuration tutorial at: https://github.com/FasterXML/jackson-databind


Make sure that you place the @JsonIgnoreProperties(ignoreUnknown = true) annotation to the parent POJO class which you want to populate as a result of parsing the JSON response and not the class where the conversion from JSON to Java Object is taking place.


As stated above the annotations only works if this is specified in the parent POJO class and not the class where the conversion from JSON to Java Object is taking place.

The other alternative without touching the parent class and causing disruptions is to implement your own mapper config only for the mapper methods you need for this.

Also the package of the Deserialization feature has been moved. DeserializationConfig.FAIL_ON_UNKNOWN_PROPERTIES to DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES

import org.codehaus.jackson.map.DeserializationConfig;
...
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

For whom are using Spring Boot, you can configure the default behaviour of Jackson by using the Jackson2ObjectMapperBuilder.

For example :

@Bean
public Jackson2ObjectMapperBuilder configureObjectMapper() {
    Jackson2ObjectMapperBuilder oMapper = new Jackson2ObjectMapperBuilder();
    oMapper.failOnUnknownProperties(false);
    return oMapper;
}

Then you can autowire the ObjectMapper everywhere you need it (by default, this object mapper will also be used for http content conversion).


I'm using jackson-xxx 2.8.5.Maven Dependency like:

<dependencies>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.5</version>
    </dependency>

</dependencies>

First,If you want ignore unknown properties globally.you can config ObjectMapper.
Like below:

ObjectMapper objectMapper = new ObjectMapper();

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

If you want ignore some class,you can add annotation @JsonIgnoreProperties(ignoreUnknown = true) on your class like:

@JsonIgnoreProperties(ignoreUnknown = true)
public class E1 {

    private String t1;

    public String getT1() {
        return t1;
    }

    public void setT1(String t1) {
        this.t1 = t1;
    }
}

You can annotate the specific property in your POJO with @JsonIgnore.

참고URL : https://stackoverflow.com/questions/5455014/ignoring-new-fields-on-json-objects-using-jackson

반응형