我是Java的新手,我遇到了将json数据转换为java对象的问题。让我们说我的json格式是
{
"totalSize" : 2,
"done" : true,
"Id" : "xyz",
"Name" : "P0000005239",
"child" : {
"Type" : "someType",
"Region" : "someRegion",
"Name" : "C001906"
},
"Address_1" : "Address_1",
"Address_2" : "Address_1"
}
如果我的java类结构是这样的,则反序列化正在运行
//Working class Structure
class Demo{
int total_Size;
boolean flag_done;
String ID;
String p_name;
Child child;
String Address1;
String Address2;
//getter and setter
}
但我的班级结构是(我无法映射我的json)
//Not Working
class Demo{
int total_Size;
boolean flag_done;
String ID;
String p_name;
String c_type;
String c_region;
String c_name;
String Address1;
String Address2;
//getter and setter
}
错误
Invocation of init method failed; nested exception is
com.google.gson.JsonParseException: The JsonDeserializer
com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@4b28f983 failed to
deserialized json object
如何从json创建具有单个类中所有数据的java对象(即单个类中的父节点和子节点数据,而不声明单独的子类)
我正在使用带有@SerializedName注释的GSON将json转换为java对象。如果您需要更多详细信息,请与我们联系。
答案 0 :(得分:1)
尝试使用fastxml jackson
为此,您需要在JSON中传递其他信息:
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME,
include=JsonTypeInfo.As.PROPERTY, property="@type")
class Base {
...
}
然后在序列化时,它将添加@type字段:
objectMapper.registerSubtypes(
new NamedType(ConcreteAAdapter.class, "ConcreteA"),
new NamedType(ConcreteBAdapter.class, "ConcreteB"),
new NamedType(ConcreteCAdapter.class, "ConcreteC")
);
//注意,对于列表,您需要明确传递TypeReference
objectMapper.writerWithType(new TypeReference<List<Base>>() {})
.writeValueAsString(someList);
{
"@type" : "ConcreteA",
...
}
on deserialization it will be:
objectMapper.registerSubtypes(
new NamedType(ConcreteA.class, "ConcreteA"),
new NamedType(ConcreteB.class, "ConcreteB"),
new NamedType(ConcreteC.class, "ConcreteC")
);
objectMapper.readValue(....)
更多信息:http://wiki.fasterxml.com/JacksonPolymorphicDeserialization