Aplicaciones Prácticas y Casos de Uso en el Mundo Real
Ahora que comprende cómo configurar ObjectMapper para ignorar propiedades desconocidas, exploremos algunas aplicaciones prácticas y escenarios del mundo real donde esta característica es útil.
1. Consumo de APIs de Terceros
Al integrarse con APIs externas, a menudo no tiene control sobre los cambios en su formato de respuesta. Al configurar ObjectMapper para ignorar propiedades desconocidas, su aplicación puede continuar funcionando incluso si la API agrega nuevos campos.
Creemos un ejemplo simple que simula el consumo de una API del clima:
- Cree un nuevo archivo en
~/project/src/main/java/com/labex/json/WeatherData.java
- Agregue el siguiente código al archivo:
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 +
'}';
}
}
- Cree un nuevo archivo en
~/project/src/main/java/com/labex/json/WeatherApiConsumer.java
- Agregue el siguiente código al archivo:
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());
}
}
}
- Compile y ejecute esta clase:
cd ~/project
mvn compile exec:java -Dexec.mainClass="com.labex.json.WeatherApiConsumer"
Debería ver una salida similar a:
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}
Observe cómo nuestra aplicación continúa funcionando con la respuesta de la API actualizada, incluso si contiene campos adicionales que nuestra clase WeatherData no define.
2. Manejo de Diferentes Versiones de API
Otro escenario común es cuando necesita admitir múltiples versiones de una API con el mismo código de cliente:
- Cree un nuevo archivo en
~/project/src/main/java/com/labex/json/ApiVersionDemo.java
- Agregue el siguiente código al archivo:
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());
}
}
}
- Compile y ejecute esta clase:
cd ~/project
mvn compile exec:java -Dexec.mainClass="com.labex.json.ApiVersionDemo"
Debería ver una salida similar a:
Parsing API v1 response:
Person{name='John Doe', age=30}
Parsing API v2 response with the same class:
Person{name='John Doe', age=30}
Este ejemplo demuestra cómo configurar ObjectMapper para ignorar propiedades desconocidas le permite manejar diferentes versiones de una API con las mismas clases Java, lo que hace que su código sea más mantenible y adaptable a los cambios.