[英]Deserializing parent and child node data of json in a single java object
I am new to Java and I am facing problem converting json data to java object. 我是Java的新手,我面临将json数据转换为java对象的问题。 Lets say my json format is
可以说我的json格式是
{
"totalSize" : 2,
"done" : true,
"Id" : "xyz",
"Name" : "P0000005239",
"child" : {
"Type" : "someType",
"Region" : "someRegion",
"Name" : "C001906"
},
"Address_1" : "Address_1",
"Address_2" : "Address_1"
}
If my java class structure is like this, deserialization is working 如果我的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
}
But my class structure is(to which I am not able to map my json) 但是我的类结构是(我无法将我的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
}
Error 错误
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
How to create java object from json having all the data in single class(ie parent and child node data in single class without declaring separate child class) 如何从具有所有数据在单个类中的json创建Java对象(即,单个类中的父节点和子节点数据,而无需声明单独的子类)
I am using GSON with @SerializedName annotation for converting json into java object. 我正在使用带有@SerializedName批注的GSON将JSON转换为Java对象。 Please let me know if you need more detail.
如果您需要更多详细信息,请告诉我。
Try using fasterxml jackson 尝试使用fasterxml jackson
For this purpose you need to pass additional info in JSON: 为此,您需要在JSON中传递其他信息:
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME,
include=JsonTypeInfo.As.PROPERTY, property="@type")
class Base {
...
}
Then on serialization it will add @type field: 然后在序列化时将添加@type字段:
objectMapper.registerSubtypes(
new NamedType(ConcreteAAdapter.class, "ConcreteA"),
new NamedType(ConcreteBAdapter.class, "ConcreteB"),
new NamedType(ConcreteCAdapter.class, "ConcreteC")
);
// note, that for lists you need to pass TypeReference explicitly //注意,对于列表,您需要显式传递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(....)
More here: http://wiki.fasterxml.com/JacksonPolymorphicDeserialization 此处更多信息: http : //wiki.fasterxml.com/JacksonPolymorphicDeserialization
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.