소개
Java 개발에서 JSON 데이터를 다루는 것은 흔한 요구 사항입니다. Jackson 라이브러리의 ObjectMapper 클래스는 Java 객체와 JSON 간의 변환을 위한 강력한 도구입니다. 하지만 JSON 데이터를 처리할 때, Java 클래스에 정의되지 않은 속성을 만날 수 있습니다. 이는 역직렬화 (deserialization) 중에 예외를 발생시킬 수 있습니다.
이 Lab 에서는 JSON 데이터에서 알 수 없는 속성을 무시하도록 ObjectMapper를 구성하는 방법을 안내합니다. 시간이 지남에 따라 변경될 수 있는 외부 데이터 소스를 처리할 때 애플리케이션의 견고성을 높이는, JSON 을 우아하게 처리하는 방법을 배우게 됩니다.
JSON 및 ObjectMapper 기본 사항 이해
알 수 없는 속성을 처리하는 방법에 대해 알아보기 전에, 먼저 JSON 이 무엇인지, 그리고 Java 에서 Jackson ObjectMapper를 사용하는 방법을 이해해 보겠습니다.
JSON 이란 무엇인가요?
JSON (JavaScript Object Notation) 은 사람이 읽고 쓰기 쉽고, 기계가 파싱하고 생성하기 쉬운 경량 데이터 교환 형식입니다. 키 - 값 쌍으로 구성되어 있으며, 웹 애플리케이션과 서버 간에 데이터를 전송하는 데 일반적으로 사용됩니다.
다음은 JSON 객체의 간단한 예시입니다.
{
"name": "John Doe",
"age": 30,
"email": "john.doe@example.com"
}
Jackson ObjectMapper 소개
Jackson 라이브러리는 Java 에서 가장 인기 있는 JSON 처리 라이브러리 중 하나입니다. ObjectMapper 클래스는 Java 객체와 JSON 간의 변환 기능을 제공하는 Jackson 의 핵심 구성 요소입니다.
간단한 Java 클래스를 만들고 ObjectMapper를 사용하여 JSON 으로, 그리고 JSON 에서 변환해 보겠습니다.
먼저, 다음 단계를 따라 Person 클래스를 생성합니다.
- WebIDE 를 열고 탐색기 (explorer view) 로 이동합니다.
~/project/src/main/java/com/labex/json/Person.java에 새 파일을 생성합니다.- 파일에 다음 코드를 추가합니다.
package com.labex.json;
public class Person {
private String name;
private int age;
// Default constructor needed for Jackson
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
이제 ObjectMapper를 사용하는 방법을 보여주는 Java 클래스를 만들어 보겠습니다.
~/project/src/main/java/com/labex/json/ObjectMapperDemo.java에 새 파일을 생성합니다.- 파일에 다음 코드를 추가합니다.
package com.labex.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class ObjectMapperDemo {
public static void main(String[] args) {
try {
// Create a Person object
Person person = new Person("John Doe", 30);
// Create an ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
// Serialize Person object to JSON string
String jsonString = objectMapper.writeValueAsString(person);
System.out.println("Serialized to JSON: " + jsonString);
// Deserialize JSON string back to Person object
Person deserializedPerson = objectMapper.readValue(jsonString, Person.class);
System.out.println("Deserialized from JSON: " + deserializedPerson);
} catch (IOException e) {
e.printStackTrace();
}
}
}
이제 이 클래스를 컴파일하고 실행해 보겠습니다.
- WebIDE 에서 터미널을 엽니다.
- 아직 해당 디렉토리에 있지 않다면 프로젝트 디렉토리로 이동합니다.
cd ~/project - 클래스를 컴파일하고 실행합니다.
mvn compile exec:java -Dexec.mainClass="com.labex.json.ObjectMapperDemo"
다음과 유사한 출력을 볼 수 있습니다.
Serialized to JSON: {"name":"John Doe","age":30}
Deserialized from JSON: Person{name='John Doe', age=30}
이는 ObjectMapper의 기본 기능을 보여줍니다.
- 직렬화 (Serialization): Java 객체를 JSON 문자열로 변환
- 역직렬화 (Deserialization): JSON 문자열을 다시 Java 객체로 변환
다음 단계에서는 JSON 에 Java 클래스에 정의되지 않은 속성이 포함되어 있을 때 어떤 일이 발생하는지, 그리고 이를 처리하는 방법을 살펴보겠습니다.
알 수 없는 속성의 문제
실제 세계에서 JSON 데이터는 종종 시간이 지남에 따라 진화합니다. API 는 새로운 필드를 추가하거나, 다른 시스템은 추가 정보를 포함할 수 있습니다. Java 클래스와 일치하지 않는 속성을 가진 JSON 을 수신하면 Jackson 의 기본 동작은 예외를 발생시키는 것입니다.
이 문제를 실제로 살펴보겠습니다.
~/project/src/main/java/com/labex/json/UnknownPropertiesDemo.java에 새 파일을 생성합니다.- 파일에 다음 코드를 추가합니다.
package com.labex.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class UnknownPropertiesDemo {
public static void main(String[] args) {
try {
// Create a JSON string with an extra property not in our Person class
String jsonWithExtraProperty = "{\"name\":\"John Doe\",\"age\":30,\"email\":\"john.doe@example.com\"}";
// Create an ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
System.out.println("Attempting to deserialize JSON with an extra 'email' property...");
// Try to deserialize the JSON into a Person object
Person person = objectMapper.readValue(jsonWithExtraProperty, Person.class);
// This line won't be reached if an exception occurs
System.out.println("Successfully deserialized: " + person);
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
}
}
}
- 이 클래스를 컴파일하고 실행합니다.
cd ~/project mvn compile exec:java -Dexec.mainClass="com.labex.json.UnknownPropertiesDemo"
다음과 유사한 오류 출력을 볼 수 있습니다.
Attempting to deserialize JSON with an extra 'email' property...
Error occurred: Unrecognized field "email" (class com.labex.json.Person), not marked as ignorable (2 known properties: "name", "age"])
이 오류는 Person 클래스에 email 속성이 없지만 JSON 문자열에는 있기 때문에 발생합니다. 기본적으로 Jackson 의 ObjectMapper는 인식하지 못하는 속성을 만나면 예외를 발생시킵니다.
많은 실제 시나리오에서 애플리케이션이 더 유연하고 이러한 상황을 적절하게 처리하기를 원합니다. 여기서 ObjectMapper를 구성하여 알 수 없는 속성을 무시하는 것이 유용해집니다.
ObjectMapper 를 구성하여 알 수 없는 속성 무시하기
이제 문제를 이해했으므로, 예외를 발생시키는 대신 ObjectMapper를 구성하여 알 수 없는 속성을 무시하는 방법을 알아보겠습니다.
ObjectMapper를 구성하여 알 수 없는 속성을 무시하는 두 가지 주요 방법이 있습니다.
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES와 함께configure()메서드 사용- Java 클래스에서 어노테이션 사용
두 가지 접근 방식을 모두 구현해 보겠습니다.
방법 1: configure() 메서드 사용
이 방법은 역직렬화되는 모든 클래스에 대해 모든 알 수 없는 속성을 무시하도록 ObjectMapper 인스턴스를 구성합니다.
~/project/src/main/java/com/labex/json/IgnoreUnknownDemo.java에 새 파일을 생성합니다.- 파일에 다음 코드를 추가합니다.
package com.labex.json;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class IgnoreUnknownDemo {
public static void main(String[] args) {
try {
// Create a JSON string with an extra property not in our Person class
String jsonWithExtraProperty = "{\"name\":\"John Doe\",\"age\":30,\"email\":\"john.doe@example.com\"}";
// Create an ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
// Configure ObjectMapper to ignore unknown properties
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
System.out.println("Attempting to deserialize JSON with an extra 'email' property...");
// Deserialize the JSON into a Person object
Person person = objectMapper.readValue(jsonWithExtraProperty, Person.class);
// This should now work without throwing an exception
System.out.println("Successfully deserialized: " + person);
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
}
}
}
- 이 클래스를 컴파일하고 실행합니다.
cd ~/project mvn compile exec:java -Dexec.mainClass="com.labex.json.IgnoreUnknownDemo"
다음과 유사한 출력을 볼 수 있습니다.
Attempting to deserialize JSON with an extra 'email' property...
Successfully deserialized: Person{name='John Doe', age=30}
이제 역직렬화가 성공하고 email 속성이 단순히 무시되는 것을 확인하세요. JSON 에 추가 속성이 있어도 애플리케이션은 계속 작동합니다.
방법 2: 어노테이션 사용
더 세밀한 제어가 필요한 경우 Jackson 어노테이션을 사용하여 클래스 수준에서 동작을 지정할 수 있습니다.
~/project/src/main/java/com/labex/json/PersonWithAnnotation.java에 새 파일을 생성합니다.- 파일에 다음 코드를 추가합니다.
package com.labex.json;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class PersonWithAnnotation {
private String name;
private int age;
// Default constructor needed for Jackson
public PersonWithAnnotation() {
}
public PersonWithAnnotation(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "PersonWithAnnotation{name='" + name + "', age=" + age + "}";
}
}
- 이제 이 접근 방식을 테스트하기 위한 데모 클래스를 생성합니다.
~/project/src/main/java/com/labex/json/AnnotationDemo.java에 새 파일을 생성합니다.- 파일에 다음 코드를 추가합니다.
package com.labex.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class AnnotationDemo {
public static void main(String[] args) {
try {
// Create a JSON string with an extra property
String jsonWithExtraProperty = "{\"name\":\"John Doe\",\"age\":30,\"email\":\"john.doe@example.com\"}";
// Create an ObjectMapper instance (no special configuration needed)
ObjectMapper objectMapper = new ObjectMapper();
System.out.println("Attempting to deserialize JSON with an extra 'email' property...");
// Deserialize the JSON into a PersonWithAnnotation object
PersonWithAnnotation person = objectMapper.readValue(jsonWithExtraProperty, PersonWithAnnotation.class);
// This should work without throwing an exception
System.out.println("Successfully deserialized: " + person);
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
}
}
}
- 이 클래스를 컴파일하고 실행합니다.
cd ~/project mvn compile exec:java -Dexec.mainClass="com.labex.json.AnnotationDemo"
다음과 유사한 출력을 볼 수 있습니다.
Attempting to deserialize JSON with an extra 'email' property...
Successfully deserialized: PersonWithAnnotation{name='John Doe', age=30}
@JsonIgnoreProperties(ignoreUnknown = true) 어노테이션은 JSON 을 이 클래스의 인스턴스로 역직렬화할 때 Jackson 에게 알 수 없는 속성을 무시하도록 지시합니다. 이 접근 방식은 전체 ObjectMapper를 구성하는 것보다 더 구체적입니다.
실용적인 응용 프로그램 및 실제 사용 사례
이제 ObjectMapper를 구성하여 알 수 없는 속성을 무시하는 방법을 이해했으므로, 이 기능이 유용한 몇 가지 실용적인 응용 프로그램과 실제 시나리오를 살펴보겠습니다.
1. 타사 API 사용
외부 API 와 통합할 때 응답 형식 변경을 제어할 수 없는 경우가 많습니다. ObjectMapper를 구성하여 알 수 없는 속성을 무시하면 API 가 새로운 필드를 추가하더라도 애플리케이션이 계속 작동할 수 있습니다.
날씨 API 를 사용하는 것을 시뮬레이션하는 간단한 예제를 만들어 보겠습니다.
~/project/src/main/java/com/labex/json/WeatherData.java에 새 파일을 생성합니다.- 파일에 다음 코드를 추가합니다.
package com.labex.json;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class WeatherData {
private String city;
private double temperature;
private int humidity;
// Default constructor needed for Jackson
public WeatherData() {
}
// Getters and setters
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public int getHumidity() {
return humidity;
}
public void setHumidity(int humidity) {
this.humidity = humidity;
}
@Override
public String toString() {
return "WeatherData{" +
"city='" + city + '\'' +
", temperature=" + temperature +
", humidity=" + humidity +
'}';
}
}
~/project/src/main/java/com/labex/json/WeatherApiConsumer.java에 새 파일을 생성합니다.- 파일에 다음 코드를 추가합니다.
package com.labex.json;
import com.fasterxml.jackson.databind.ObjectMapper;
public class WeatherApiConsumer {
public static void main(String[] args) {
try {
// Create an ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
// Simulate an initial API response with just the basics
String initialApiResponse = "{\"city\":\"New York\",\"temperature\":72.5,\"humidity\":65}";
// Parse the response
WeatherData weatherData = objectMapper.readValue(initialApiResponse, WeatherData.class);
System.out.println("Initial weather data: " + weatherData);
// Now simulate the API adding new fields in a future version
String updatedApiResponse =
"{\"city\":\"New York\",\"temperature\":72.5,\"humidity\":65," +
"\"wind_speed\":10.2,\"pressure\":1013.25,\"forecast\":\"sunny\"}";
// Parse the updated response with the same object model
WeatherData updatedWeatherData = objectMapper.readValue(updatedApiResponse, WeatherData.class);
System.out.println("Updated weather data (with ignored fields): " + updatedWeatherData);
// Notice how our application continues to work without changes to our model
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
}
}
}
- 이 클래스를 컴파일하고 실행합니다.
cd ~/project mvn compile exec:java -Dexec.mainClass="com.labex.json.WeatherApiConsumer"
다음과 유사한 출력을 볼 수 있습니다.
Initial weather data: WeatherData{city='New York', temperature=72.5, humidity=65}
Updated weather data (with ignored fields): WeatherData{city='New York', temperature=72.5, humidity=65}
WeatherData 클래스에 정의되지 않은 추가 필드가 포함되어 있음에도 불구하고 애플리케이션이 업데이트된 API 응답으로 계속 작동하는 것을 확인하세요.
2. 다른 API 버전 처리
또 다른 일반적인 시나리오는 동일한 클라이언트 코드를 사용하여 여러 버전의 API 를 지원해야 하는 경우입니다.
~/project/src/main/java/com/labex/json/ApiVersionDemo.java에 새 파일을 생성합니다.- 파일에 다음 코드를 추가합니다.
package com.labex.json;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ApiVersionDemo {
public static void main(String[] args) {
try {
// Create an ObjectMapper that ignores unknown properties
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// API v1 response
String apiV1Response = "{\"name\":\"John Doe\",\"age\":30}";
// API v2 response with additional fields
String apiV2Response =
"{\"name\":\"John Doe\",\"age\":30,\"email\":\"john.doe@example.com\"," +
"\"address\":\"123 Main St\",\"phone\":\"555-1234\"}";
// We can use the same Person class for both versions
System.out.println("Parsing API v1 response:");
Person personV1 = objectMapper.readValue(apiV1Response, Person.class);
System.out.println(personV1);
System.out.println("\nParsing API v2 response with the same class:");
Person personV2 = objectMapper.readValue(apiV2Response, Person.class);
System.out.println(personV2);
// Both work fine with our simple Person class
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
}
}
}
- 이 클래스를 컴파일하고 실행합니다.
cd ~/project mvn compile exec:java -Dexec.mainClass="com.labex.json.ApiVersionDemo"
다음과 유사한 출력을 볼 수 있습니다.
Parsing API v1 response:
Person{name='John Doe', age=30}
Parsing API v2 response with the same class:
Person{name='John Doe', age=30}
이 예제는 ObjectMapper를 구성하여 알 수 없는 속성을 무시함으로써 동일한 Java 클래스를 사용하여 다른 버전의 API 를 처리하는 방법을 보여줍니다. 이를 통해 코드를 더 유지 관리하고 변경 사항에 적응할 수 있습니다.
모범 사례 및 추가 구성 옵션
이제 ObjectMapper를 구성하여 알 수 없는 속성을 무시하는 방법을 이해했으므로, 실제 응용 프로그램에서 유용할 수 있는 몇 가지 모범 사례와 추가 구성 옵션에 대해 논의해 보겠습니다.
모범 사례
1. 애플리케이션에 적합한 접근 방식 선택
- 전역 구성: 모든 역직렬화 작업에서 알 수 없는 속성을 무시하려면
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)를 사용합니다. - 클래스 수준 어노테이션: 특정 클래스만 알 수 없는 속성을 무시하려면
@JsonIgnoreProperties(ignoreUnknown = true)를 사용합니다.
2. 오류 처리 및 로깅 고려
알 수 없는 속성을 무시하는 경우에도 특히 개발 또는 테스트 환경에서 알 수 없는 속성이 발견될 때 로깅하는 것이 유용할 수 있습니다.
알 수 없는 속성에 대한 사용자 정의 처리가 있는 예제를 만들어 보겠습니다.
~/project/src/main/java/com/labex/json/LoggingUnknownPropertiesDemo.java에 새 파일을 생성합니다.- 파일에 다음 코드를 추가합니다.
package com.labex.json;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;
import java.io.IOException;
public class LoggingUnknownPropertiesDemo {
public static void main(String[] args) {
try {
// Create a JSON string with an extra property
String jsonWithExtraProperty =
"{\"name\":\"John Doe\",\"age\":30,\"email\":\"john.doe@example.com\"}";
// Create an ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
// Configure ObjectMapper to ignore unknown properties
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// Add a problem handler to log unknown properties
objectMapper.addHandler(new DeserializationProblemHandler() {
@Override
public boolean handleUnknownProperty(DeserializationContext ctxt,
JsonParser p,
com.fasterxml.jackson.databind.JsonDeserializer<?> deserializer,
Object beanOrClass,
String propertyName) throws IOException {
System.out.println("WARNING: Unknown property '" + propertyName +
"' found during deserialization of " +
beanOrClass.getClass().getSimpleName());
// Skip the value and continue
p.skipChildren();
return true;
}
});
// Deserialize the JSON into a Person object
Person person = objectMapper.readValue(jsonWithExtraProperty, Person.class);
System.out.println("Successfully deserialized: " + person);
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
}
}
}
- 이 클래스를 컴파일하고 실행합니다.
cd ~/project mvn compile exec:java -Dexec.mainClass="com.labex.json.LoggingUnknownPropertiesDemo"
다음과 유사한 출력을 볼 수 있습니다.
WARNING: Unknown property 'email' found during deserialization of Person
Successfully deserialized: Person{name='John Doe', age=30}
이 접근 방식을 사용하면 알 수 없는 속성을 무시하면서도 해당 속성의 존재를 인식할 수 있으므로 디버깅 또는 모니터링 목적으로 유용할 수 있습니다.
추가 구성 옵션
Jackson 의 ObjectMapper는 다른 많은 유용한 구성 옵션을 제공합니다. 알 수 없는 속성을 무시하는 것과 함께 자주 사용되는 몇 가지 옵션은 다음과 같습니다.
~/project/src/main/java/com/labex/json/AdditionalConfigurationsDemo.java에 새 파일을 생성합니다.- 파일에 다음 코드를 추가합니다.
package com.labex.json;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class AdditionalConfigurationsDemo {
public static void main(String[] args) {
try {
// Create a Person object
Person person = new Person("John Doe", 30);
// Create an ObjectMapper with various configurations
ObjectMapper objectMapper = new ObjectMapper();
// Ignore unknown properties during deserialization
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// Allow JSON with single quotes
objectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
// Allow JSON with unquoted field names
objectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// Format output JSON with indentation for better readability
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
// Serialize the Person object to JSON with pretty printing
String jsonString = objectMapper.writeValueAsString(person);
System.out.println("Formatted JSON:");
System.out.println(jsonString);
// Parse JSON with single quotes and unquoted field names
String nonStandardJson = "{'name':'Jane Smith', age:25}";
Person parsedPerson = objectMapper.readValue(nonStandardJson, Person.class);
System.out.println("\nParsed from non-standard JSON: " + parsedPerson);
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
}
}
}
- 이 클래스를 컴파일하고 실행합니다.
cd ~/project mvn compile exec:java -Dexec.mainClass="com.labex.json.AdditionalConfigurationsDemo"
다음과 유사한 출력을 볼 수 있습니다.
Formatted JSON:
{
"name" : "John Doe",
"age" : 30
}
Parsed from non-standard JSON: Person{name='Jane Smith', age=25}
이 예제는 다양한 구성 옵션을 보여줍니다.
SerializationFeature.INDENT_OUTPUT: 들여쓰기를 사용하여 생성된 JSON 을 더 읽기 쉽게 만듭니다.ALLOW_SINGLE_QUOTES: 이중 따옴표 대신 작은 따옴표가 있는 JSON 을 허용합니다.ALLOW_UNQUOTED_FIELD_NAMES: 따옴표 없이 필드 이름을 허용합니다.
이러한 추가 구성은 비표준 JSON 으로 작업하거나 JSON 출력을 더 사람이 읽을 수 있도록 해야 하는 경우와 같은 다양한 시나리오에서 유용할 수 있습니다.
요약
이 랩에서는 외부 소스에서 JSON 데이터를 처리하는 강력한 Java 애플리케이션을 구축하는 데 필수적인 기술인 Jackson 의 ObjectMapper를 구성하여 JSON 데이터의 알 수 없는 속성을 무시하는 방법을 배웠습니다.
다음 사항을 숙달했습니다.
- Jackson 의
ObjectMapper를 사용한 기본적인 JSON 직렬화 및 역직렬화 - JSON 에서 알 수 없는 속성의 문제와 예외가 발생하는 이유
- 알 수 없는 속성을 처리하는 두 가지 접근 방식:
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)를 사용한 전역 구성@JsonIgnoreProperties(ignoreUnknown = true)를 사용한 클래스 수준 어노테이션
- 실용적인 응용 프로그램 및 실제 사용 사례:
- 시간이 지남에 따라 변경될 수 있는 타사 API 사용
- 동일한 코드로 여러 버전의 API 지원
- 모범 사례 및 추가 구성 옵션:
- 역직렬화 중 알 수 없는 속성 로깅
- 다양한 JSON 형식 및 출력 스타일에 대한
ObjectMapper구성
이러한 기술은 데이터 형식이 변경되거나 예상치 못한 속성이 포함된 경우에도 다양한 소스에서 JSON 데이터를 원활하게 처리할 수 있는 더 탄력적인 Java 애플리케이션을 구축하는 데 도움이 됩니다.
추가 학습을 위해 사용자 지정 직렬 변환기 및 역직렬 변환기, 날짜 형식 처리, 다형성 유형 처리와 같이 더 복잡한 JSON 처리 시나리오에 도움이 될 수 있는 다른 Jackson 어노테이션 및 기능을 살펴보세요.



