実用的なアプリケーションと現実世界のユースケース
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 バージョンの処理
もう 1 つの一般的なシナリオは、同じクライアントコードで複数のバージョンの 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 を処理できることを示しています。これにより、コードの保守性が向上し、変更への適応性が高まります。