I´m having some problems when i try to deserializing a Java class.
My classes are :
Abstract Class A {
Long ID
String name
...
}
Class B extends A{
String Type
String Value
}
Class C extends A{
List<A> typedList;
}
And my Serialization/Deseralization Methods:
public String serialize(T object) {
String returnValue = "";
try {
returnValue = mapper.writeValueAsString(object);
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(returnValue);
return returnValue;
}
public List<T> unserialize(String data, Class<?> clazz) {
List<T> returnValue = new LinkedList<T>();
//JavaType topMost = mapper.getTypeFactory().constructParametricType(MyWrapper.class, ActualClassRuntime.class);
try {
returnValue = (List<T>) mapper.readValue(data,clazz);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returnValue;
}
The list inside the C class contain B and C elements. Serialization is done without problems but when i tried to deserialize C , Jackson can´t rebuild my typedList correctly.
It uses LinkedHashMap instead of LinkedList and don´t use the correct types.
Any ideias how to solve this ?
Thanks in advance!
If you expect to get a List, you must pass a List type: here you are giving type of
clazzbut expect type ofList<T>. This won’t work, even ifclazzis of typeList.So you need to pass proper type. But for List (and Map) types, you further need to specify contents type: and type variable does not do. What works is something like:
where
TypeReferencemust be used due to Java type erasure.You can also construct structured types from components dynamically, if they are passed as arguments:
The reason you get
LinkedHashMapis just because of missing type information: if JSON Object is encountered, and requested type isjava.lang.Object(as would be the case if you just passed typeList.classto bind to), this is the type that would be used.