我有一个固定文件person.json
,
{
"fistName": "John"
"lastName": "Smith"
}
我有一个名为 Person 的类
public class Person {
private String firstName;
private String lastName;
//.. getters and setters
}
我使用 ObjectMapper
反序列化 Person
,如下所示
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);
。
我的问题是为什么会出现此错误以及如何解决它?
最佳答案
因为你要求 jackson 使用naming strategy将驼峰式大小写(即 firstName
)转换为带下划线的小写字母,即 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"
}
输出:
Person(firstName=John, lastName=Smith)
关于java - 使用 ObjectMapper 反序列化对象时将驼峰命名法转换为下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31861541/