If you had a field in your JSON that tells you what kind of object you are trying to parse, it will be "easier", however, since in your data your can distinguish object by field structure, you can parse your JSON according to it. I mean, if you have accountid
field, it's an Account class, and so on.
So, what your have to do, is to look into your JSON and decide what kind of class you want to use to deserialize. To do something like that, you can use JsonParser
class that returns you a browsable tree of objects and then fire a standard Gson deserialization.
I prepared a code that you can copy&run in your IDE to show how to do it.
package stackoverflow.questions.q19997365;
import com.google.gson.*;
public class Q19997365 {
public static class Person {
String id;
String name;
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
}
public static class Account {
String accountid;
String accountnumber;
@Override
public String toString() {
return "Account [accountid=" + accountid + ", accountNumber=" + accountnumber + "]";
}
}
public static class Transaction {
String id;
String date;
@Override
public String toString() {
return "Transaction [id=" + id + ", date=" + date + "]";
}
}
/**
* @param args
*/
public static void main(String[] args) {
String json1 = "{\"id\" : \"1\", \"name\" : \"David\"}"; // this represent testdata for the class Person
String json2 = "{\"accountid\" : \"1188\", \"accountnumber\" : \"119295567\"}"; // this represent testdata for the class account
String json3 = "{\"id\" : \"22\", \"date\" : \"22.11.2013\"}"; // this represent testdata for the class transaction
System.out.println(extractFromJson(json1));
System.out.println(extractFromJson(json2));
System.out.println(extractFromJson(json3));
}
private static Object extractFromJson(String json) {
Gson g = new Gson();
JsonObject e = new JsonParser().parse(json).getAsJsonObject();
if (e.get("name") != null)
return g.fromJson(json, Person.class);
if (e.get("accountid") != null)
return g.fromJson(json, Account.class);
if (e.get("date") != null)
return g.fromJson(json, Transaction.class);
return null;
}
}
and this is my execution:
Person [id=1, name=David]
Account [accountid=1188, accountnumber=119295567]
Transaction [id=22, date=22.11.2013]
The key part is extractFromJson method that does all the job. It uses a JsonParser
to snoop into the JSON string and then calls a Gson instance to do the right deserialization.
Three final notes
- the method instantiates Gson every time, is not efficient, but here I want to show you the concept, you can easily improve this.
- your
date
field is not a kind of date that Gson can parse by default, you need change date format for that, see this for example
extractFromJson
method is something like a factory pattern, in this pattern you cannot know what kind of object will be returned. So Object
is the return type, you need an instanceof
+ cast to manage it correctly.