Tôi đã một lớp trông như thế này:
public class Person {
public class Address {
private String line1;
private String line2;
private String zipCode;
private String state;
// standard public getters and setters for the class here
}
private String name;
private String address;
// standard public getters and setters for the class here
}
và dưới đây là cách Tôi đang sử dụng jackson với nó.
public class JsonTest {
public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass)
throws JsonMappingException, JsonParseException, IOException {
return m.readValue(jsonAsString, pojoClass);
}
public static String toJson(Object pojo, boolean prettyPrint)
throws JsonMappingException, JsonGenerationException, IOException {
StringWriter sw = new StringWriter();
JsonGenerator jg = jf.createJsonGenerator(sw);
if (prettyPrint) {
jg.useDefaultPrettyPrinter();
}
m.writeValue(jg, pojo);
return sw.toString();
}
public static void main(String[] args) {
Person p = new Person();
String json = this.toJson(p, true); // converts ‘p’ to JSON just fine
Person personFromJson = this.fromJson(json, Person.class); // throws exception!!!
}
}
dòng thứ 3 của phương thức main (nơi tôi cố gắng để chuyển đổi json để đối tượng Person), ném ngoại lệ này:
IOException: Can not deserialize Class com.mycompany.models.Person$Address (of type non-static member class) as a Bean
những gì tôi làm sai?
Có vẻ như bạn không thể tuần tự hóa các lớp như vậy, hãy xem http://www.cowtowncoder.com/blog/archives/2010/08/entry_411.html để biết chi tiết –
@Stas Kurilin - Bạn nên biến nhận xét đó thành câu trả lời, cái đúng của nó. – Perception
@Perception, done. Nhưng tôi hy vọng smb có thể giúp ishaq theo cách tốt hơn. –