2

I have a JSON file like this:

{"id" : "1", "name" : "David"}  // this represent testdata for the class Person
{"accountid" : "1188", "accountnumber" : "119295567"}  // this represent testdata for the class account
{"id" : "22", "date" : "22.11.2013"} // this represent testdata for the class transaction

Now, I have three Java classes (with suitable attributes like in the JSON file and get- and set methods)

  • Person
  • Account
  • Transaction

I have written a Junit Test and will use the JSON file. I will generate three different objects by using only one JSON file.

How can I do this using Gson? This is what I tried so far to deserialize a Person object.

Gson gson = new GsonBuilder().create();
String jsonTestFile = FileUtils.readFileToString(new File(this.pathForJsonTestFile
         + "testFile.json"));

Person person = gson.fromJson(jsonTestFile,
         Person.class);

But how can I explicit create the account object or the transaction object or the person object depending from the JSON?

giampaolo
  • 6,906
  • 5
  • 45
  • 73
  • 2
    So far, you have posted 35 questions, most of this have 1 or more answers. You are free to accept none, if you want. But I think you should accept some of them and finally get the scholar badge :) – giampaolo Nov 15 '13 at 23:16

1 Answers1

2

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

  1. the method instantiates Gson every time, is not efficient, but here I want to show you the concept, you can easily improve this.
  2. 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
  3. 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.
Community
  • 1
  • 1
giampaolo
  • 6,906
  • 5
  • 45
  • 73