Twerterus Twerterus - 5 months ago 31
JSON Question

Serialization and deserialization of children

Let's assume I have the following structure:

abstract class foo{}
class bar1 extends foo{
int demo1 = 0;
class bar2 extends foo{
int demo1 = 0;
int demo2 = 0;
class bar3 extends foo{}

Usually when I need to send a Json, I use the following code

Gson gson = new Gson()

Recieving end

Gson gson = new Gson()
bar1 test = gson.fromJson(gsonString, bar1);

The issue here is that I need to send bar1/bar2/bar3 and get back the original object - Meaning I don't know what the current JSON should be parsed back into. Another layer of complexity is added due to the fact that an array of bar1/bar2/bar3 are being sent back.


//Issue: is the second param bar1 bar2 or bar3?
//I put a questionmark where the issues occur, due to the fact
//that I wouldn't know on the recieving side whether I'm going
//to recieve bar1/bar2/bar3
? test = gson.fromJson(gsonString, ?);

I tried storing the type in foo, but without being able to parse it back there is no way to know the type.


If you store the type in Foo like this:

private String fqcn; 

The you could first a string search on the json string when receiving to extract the fully qualified classname. Then you can use:

Foo test = gson.fromJson(gsonString, Class.forName( foundFqcn);