编程语言
首页 > 编程语言> > java – 对POJO映射不区分大小写的JSON而不更改POJO

java – 对POJO映射不区分大小写的JSON而不更改POJO

作者:互联网

有谁知道com.fasterxml.jackson.databind.ObjectMapper如何能够将JSON属性映射到不区分大小写的POJO属性?

JSON字符串:

[{“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:无法反序列化…的实例

既不能改变JSON-String也不能改变POJO-Class.

解决方法:

这种行为是在Jackson 2.5.0中引入的.您可以使用MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES将映射器配置为不区分大小写.

例如 :

ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

标签:java,json,case-insensitive,data-binding,fasterxml
来源: https://codeday.me/bug/20190923/1813746.html