我正在使用spring 3.1.2,我需要将一个json对象解析为POJO。这是我需要解析的 json:
{
"Person" : {
"id" : "2"
},
"Dog" : {
"dateOfBirth" : "2012-08-20 00:00:00",
"price" : "10.00"
}
}
我需要将这个 json 对象(由两个对象组合而成)转换为一个 POJO,这里是:
public class MyClass{
public MyClass(){}
public MyClass(String personsId, TimeStamp dogsDateOfBirth, BigDecimal dogsPrice){
.... // assign each parameter to the appropriate field
}
private String personsId;
private TimeStamp dogsDateOfBirth;
private BigDecimal dogsPrice;
//... Getters and Setters for each field
}
为此,我使用ObjectMapper mapper = new ObjectMapper();
了 Now,因为我有几个 json 对象,所以我的代码如下所示:
String json = ... ;// A json with several objects as above
JsonNode tree = mapper.readTree(json);
Iterator<JsonNode> iter = tree.path("data").getElements();
while (iter.hasNext()){
JsonNode node = iter.next();
MyClass myClass = mapper.readValue(node, MyClass.class);
... // do something with myClass object
}
当我运行它时 - 我得到以下异常:
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class ...MyClass]: can not instantiate from JSON object (need to add/enable type information?)
我试图创建一个简单的 POJO - Person
:
public class Person{
private String id;
public Person(){}
public Person(String id){
this.id = id;
}
... // Getter and Setter
}
并执行以下操作:
Person person = mapper.readValue(node.path("Person"), Person.class);
我得到这个(相同的)异常:
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class ...Person]: can not instantiate from JSON object (need to add/enable type information?)
我试图阅读一些有关类型信息的信息- 但无法理解它如何在这里帮助我。
如何将此 json 转换为我的 POJO?
谢谢。