Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deserialize JSON data for different types of objects

Im using GSON on an Android device.

I have JSON data coming in, but it can come in the form of a few different objects.

This is how I think I need to handle it.

public class Command 
{
    public String Command;  
}


String json = {"Command":"Something", "date":"now"}

String command = gson.fromJson(message, Command.class);

Then switch on command

Switch(command)
{

case: something
//deserialize to "something" object;
break;

case: other somthing
//deserialize to "other somthing" object;
break;

case: object 3
//deserialize to "object 3" object;
break;

}

Does GSON have some sort of Auto Mapping to the best suited object, so i dont have to make a custom object handler and deseraialize the String twice?

like image 726
Jason Portnoy Avatar asked Mar 25 '26 04:03

Jason Portnoy


1 Answers

I would parse it as a general JsonObject using

    JsonParser parser = new JsonParser();
    JsonObject jsonObject = parser.parse(json).getAsJsonObject();

then find something unique about each json schema and then depending on which schema convert it to a bean using

    gson.fromJson(jsonObject, AppropriateBean.class);
like image 158
Joseph Helfert Avatar answered Mar 26 '26 20:03

Joseph Helfert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!