gpt4 book ai didi

java - jackson IOException : Can not deserialize Class com. mycompany.models.Person$Address(类型为非静态成员类)作为 Bean

转载 作者:搜寻专家 更新时间:2023-10-30 21:07:11 26 4
gpt4 key购买 nike

我有一个看起来像这样的类:

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

}

下面是我如何使用 jackson 的。

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!!!
}
}

main 方法的第 3 行(我尝试将 json 转换为 Person 对象)抛出此异常:

IOException: Can not deserialize Class com.mycompany.models.Person$Address (of type non-static member class) as a Bean

我做错了什么?

最佳答案

因为内部类没有默认的零参数构造函数(它们有对外部/父类的隐藏引用)Jackson 无法实例化它们。

解决方案是使用static内部类:

public class Outer {
static class Inner {
private String foo;
public String getFoo() { return foo; }
}
}

原始答案:

实现中存在一些问题,您似乎无法序列化此类,请参阅 cowtowncoder了解详情。

关于java - jackson IOException : Can not deserialize Class com. mycompany.models.Person$Address(类型为非静态成员类)作为 Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6890796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com