Aplicações Práticas e Casos de Uso do Mundo Real
Agora que você entende como configurar o ObjectMapper para ignorar propriedades desconhecidas, vamos explorar algumas aplicações práticas e cenários do mundo real onde esse recurso é útil.
1. Consumindo APIs de Terceiros
Ao integrar com APIs externas, você frequentemente não tem controle sobre as mudanças em seu formato de resposta. Ao configurar o ObjectMapper para ignorar propriedades desconhecidas, sua aplicação pode continuar a funcionar mesmo que a API adicione novos campos.
Vamos criar um exemplo simples que simula o consumo de uma API de clima:
- Crie um novo arquivo em
~/project/src/main/java/com/labex/json/WeatherData.java
- Adicione o seguinte código ao arquivo:
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 +
'}';
}
}
- Crie um novo arquivo em
~/project/src/main/java/com/labex/json/WeatherApiConsumer.java
- Adicione o seguinte código ao arquivo:
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 e execute esta classe:
cd ~/project
mvn compile exec:java -Dexec.mainClass="com.labex.json.WeatherApiConsumer"
Você deve ver uma saída semelhante 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 como nossa aplicação continua a funcionar com a resposta da API atualizada, mesmo que ela contenha campos adicionais que nossa classe WeatherData não define.
2. Lidando com Diferentes Versões de API
Outro cenário comum é quando você precisa suportar múltiplas versões de uma API com o mesmo código cliente:
- Crie um novo arquivo em
~/project/src/main/java/com/labex/json/ApiVersionDemo.java
- Adicione o seguinte código ao arquivo:
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 e execute esta classe:
cd ~/project
mvn compile exec:java -Dexec.mainClass="com.labex.json.ApiVersionDemo"
Você deve ver uma saída semelhante 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 exemplo demonstra como configurar o ObjectMapper para ignorar propriedades desconhecidas permite que você lide com diferentes versões de uma API com as mesmas classes Java, tornando seu código mais fácil de manter e adaptável a mudanças.