使用ObjectMapper反序列化对象时,将camelCase转换为下划线

时间:2015-08-06 16:53:22

标签: java json spring deserialization

我有一个夹具文件person.json

{
   "fistName": "John"
   "lastName": "Smith"
}

我有一个名为Person的课程

public class Person {
  private String firstName;
  private String lastName;
  //.. getters and setters
}

我使用下面的Person反序列化ObjectMapper

ObjectMapper mapper = new ObjectMapper(); 
Person person = mapper.readValue(new FileInputStream(new File("person.json")),Person.class);

我收到此错误,

    java.lang.RuntimeException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: 
Unrecognized field "firstName" (class com.foo.Person), not marked as ignorable (2 known properties: , "first_name", "last_name"])

我使用
时遇到同样的错误   mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

我的问题是为什么我会收到此错误以及如何解决?

1 个答案:

答案 0 :(得分:1)

因为您要求杰克逊使用naming strategy翻译骆驼案,即firstName使用下划线({1}}来降低案例。

first_name

public class App { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(new FileInputStream(new File("/path/to/person.json")),Person.class); System.out.println(person); } } @Data // lombok @Data public class Person { private String firstName; private String lastName; } (已修复):

person.json

输出:

{
    "firstName": "John",
    "lastName": "Smith"
}