编辑:虽然我的解决方案有效,但 Selindek 的答案是最好的
根据https://jsonlint.com/,您的 Json 无效,原因有两个:
我将假设这个 JSON,带有不带引号的字段名称:
{
name: "abcd",
addressLine1: "123",
addressLine2: "1111"
}
我可以想到两种方法:
1 - 简单的地图处理
// Create your mapper, and configure it to allow unquoted field names
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// Parse the JSON to a Map
TypeReference<HashMap<String, String>> typeRef
= new TypeReference<HashMap<String, String>>() {};
Map<String, String> jsonAsMap = null;
try {
jsonAsMap = mapper.readValue(yourJsonString, typeRef);
} catch (Exception e) {
System.out.println("Something went wrong:" + e.getMessage());
}
// Read the data from the map and build your objects
Student student = null;
if(jsonAsMap != null) {
Address address = new Address();
address.setLine1(jsonAsMap.get("addressLine1"));
address.setLine2(jsonAsMap.get("addressLine2"));
student = new Student();
student.setName(jsonAsMap.get("name"));
student.setAddress(address);
System.out.println(student.getName());
System.out.println(student.getAddress().getLine1());
System.out.println(student.getAddress().getLine2());
}
2 - 使用代理对象(我更喜欢这个)
另一种方法是拥有一个代理类,您可以在其中反序列化您的 JSON,并从中构建您的学生:
class RawStudent {
private String name, addressLine1, addressLine2;
public Student toStudent() {
Address address = new Address();
address.setLine1(addressLine1);
address.setLine2(addressLine2);
Student student = new Student();
student.setName(name);
student.setAddress(address);
return student;
}
// GETTERS / SETTERS
}
并以这种方式使用它:
// Create your mapper, and configure it to allow unquoted field names
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// Parse the JSON to a RawStudent object
RawStudent rawStudent = null;
try {
rawStudent = mapper.readValue(jsonUnquoted, RawStudent.class);
} catch (Exception e) {
System.out.println("Something went wrong:" + e.getMessage());
}
// Read the data from the map and build your objects
Student student = null;
if (rawStudent != null) {
student = rawStudent.toStudent();
System.out.println(student.getName());
System.out.println(student.getAddress().getLine1());
System.out.println(student.getAddress().getLine2());
}
注意
如果您输入错误并且确实有引用的字段,即:
{
"name": "abcd",
"addressLine1": "123",
"addressLine2": "1111"
}
那你就不需要那行了
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);