不更改 POJO 的不区分大小写的 JSON 到 POJO 映射 [英] Case insensitive JSON to POJO mapping without changing the POJO
问题描述
有谁知道 com.fasterxml.jackson.databind.ObjectMapper 如何能够将 JSON 属性映射到不区分大小写的 POJO 属性?
Does anyone know how com.fasterxml.jackson.databind.ObjectMapper is able to map JSON properties to POJO properties case insensitive?
JSON 字符串:
[{"FIRSTNAME":"John","LASTNAME":"Doe","DATEOFBIRTH":"1980-07-16T18:25:00.000Z"}]
[{"FIRSTNAME":"John","LASTNAME":"Doe","DATEOFBIRTH":"1980-07-16T18:25:00.000Z"}]
POJO 类:
public class Person {
private String firstName;
private String lastName;
private Date dateOfBirth;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
测试类:
@Test
public final void testDeserializingPersonJsonToPersonClass()
throws JsonParseException, JsonMappingException, IOException {
final String jsonAsString = "[{"FIRSTNAME":"John","LASTNAME":"Doe","DATEOFBIRTH":"1980-07-16T18:25:00.000Z"}]";
final ObjectMapper mapper = new ObjectMapper();
final Person person = mapper.readValue(jsonAsString, Person.class);
assertNotNull(person);
assertThat(person.getFirstName(), equalTo("John"));
}
这最终会出现以下错误:
com.fasterxml.jackson.databind.JsonMappingException:无法反序列化...的实例
This ends up in following error:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of ...
无法更改 JSON-String 和 POJO-Class.
It's not possible to change neither JSON-String nor POJO-Class.
推荐答案
此行为是在 Jackson 2.5.0 中引入的.您可以使用 MapperFeature 将映射器配置为不区分大小写.ACCEPT_CASE_INSENSITIVE_PROPERTIES.
This behaviour was introduced in Jackson 2.5.0. You can configure the mapper to be case insensitive using MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES.
例如:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
这篇关于不更改 POJO 的不区分大小写的 JSON 到 POJO 映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!