Question
How can com.fasterxml.jackson.databind.ObjectMapper perform case insensitive mapping of JSON properties to POJO properties without changing the POJO?
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
Answer
Jackson's ObjectMapper can be configured to perform case insensitive property mapping, allowing you to deserialize JSON properties into POJO fields that differ in capitalization. This is especially useful when you cannot modify the JSON structure or the POJO definition.
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
public class JsonToPojoExample {
public static void main(String[] args) throws Exception {
String jsonAsString = "[{\"FIRSTNAME\":\"John\",\"LASTNAME\":\"Doe\",\"DATEOFBIRTH\":\"1980-07-16T18:25:00.000Z\"}]";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
Person person = mapper.readValue(jsonAsString, Person.class);
System.out.println(person.getFirstName()); // Output: John
}
}
Causes
- The default behavior of Jackson is case sensitive when mapping JSON properties to POJO fields.
- If the JSON properties' names do not match the case of the POJO's field names, a JsonMappingException will be thrown.
Solutions
- Configure the ObjectMapper to accept case insensitive properties using `MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES`.
- Use the configuration in your testing or main logic where you create and use the ObjectMapper.
Common Mistakes
Mistake: Failing to configure the ObjectMapper for case insensitivity.
Solution: Always set `MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES` to true before deserializing.
Mistake: Using the wrong JSON structure that still does not match POJO fields.
Solution: Ensure that the JSON keys correspond to the expected fields in the POJO, but with case insensitivity in mind.
Helpers
- Jackson ObjectMapper case insensitive mapping
- JSON to POJO mapping
- Java JSON deserialization
- Jackson MapperFeature
- JsonMappingException solutions