我使用杰克逊库编组了一个具有内部类(非静态)的类对象,它工作得很好。但是,在解组对象时我遇到了问题。原因是我的内部类没有任何默认构造函数。我在这里复制了示例代码:
public class JsonMarshallUnMarshall {
public static void main(String[] args) {
Person person = new Person();
person.setId(2222);
person.setName("My Name");
Person.Student student = person.new Student(44887);
person.setStudent(student);
String personJsonValue = null;
// Marshalling
System.out.println("====Marshalling====");
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(Person.Student.class, MixIn.class);
mapper.getDeserializationConfig().addMixInAnnotations(Person.Student.class, MixIn.class);
try {
personJsonValue = mapper.writeValueAsString(person);
System.out.println(personJsonValue);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// UnMarshalling
System.out.println("====Unmarshalling====");
Person unMarshalledPerson = null;
try {
unMarshalledPerson = mapper
.readValue(personJsonValue, Person.class);
System.out.println("id: " + unMarshalledPerson.getId());
System.out.println("name: " + unMarshalledPerson.getName());
System.out.println("student id: " + unMarshalledPerson.getStudent().getStudentId());
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Person {
private int id;
private String name;
private Student student;
public Person() {
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public class Student {
private int studentId;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public Student(int studentId) {
this.studentId = studentId;
}
}
}
abstract class MixIn {
public MixIn(@JsonProperty("studentId") int newStudentId) {
}
@JsonProperty("studentId")
abstract int getNewStudentId();
}
在执行代码时,我得到一个例外:
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.tnsi.cnam.batch.utilities.Person$Student]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: java.io.StringReader@1abab88; line: 1, column: 41] (through reference chain: com.tnsi.cnam.batch.utilities.Person["student"])
有没有办法解决这个问题...我不能把默认构造函数放在第一方jar的实际类中。