I have an interface, Item
. The objects Product
and Category
implement Item
. I have an ArrayList<Item>
I need to serialize and deserialize. I tried using Gson, but it does not support serilization and deserialization of interfaces. What could I do? (maybe with Gson)
Asked
Active
Viewed 477 times
0
-
Tried this: http://pastebin.com/sFQbTN3c , but it doesn't work. – Sep 05 '13 at 08:22
1 Answers
0
You need to create a serializer for the classes.
I used Gson. What I did was create a JSONValueSerializer class and interface IJSONValueSerializer (with one method toJsonString()). I then implemented JsonSerializer on the JSONValueSerializer class created.
Now from there all I had to do was implement the interface on any class I wanted to serialize and I had a common serializer for similar classes. So in your case you could implement this class on Item and the serializer will tell it how to serialize Product and Category when registered by the GsonBuilder.
private class JSONValueSerializer implements JsonSerializer<IJSONValueSerializer> {
public JsonElement serialize(IJSONValueSerializer src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toJsonString());
}
}
Then create the GsonBuilder and register any classes that are going to be serialized.
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(MyClass.class, new JSONValueSerializer());
gson.create().toJson(someObjectContainingMyClass);
https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization

MarCrazyness
- 2,172
- 1
- 27
- 28
-
I don't get it. My `Product` has got a String, an int, and a Category, and my Categories have a String and an int. Could you provide a code sample that does that? – Sep 05 '13 at 06:35
-
-
I just tried `Gson.fromJson(reader, new TypeToken
>(){}.getType());`, which doesn't work. I don't know what you mean I should do in the serialize method. – Sep 05 '13 at 06:45 -
Ah I see now. Check this out:http://stackoverflow.com/questions/5952595/serializing-list-of-interfaces-gson – MarCrazyness Sep 05 '13 at 07:06
-
By the way, what should implement the IJSONValueSerializer, the `Item` or the `Product` and `Category`? – Sep 05 '13 at 07:10
-
I was able to get it to work without the serializer and just specifying the type token as a List
vs List – MarCrazyness Sep 05 '13 at 15:49- . http://pastebin.com/M9tAVcSP