CodeMonkey
CodeMonkey

Reputation: 12444

Correct way of creating a large Json string using Gson

I'm using Gson to create a Json string. Up until now, I've been serializing a relatively small classes with a few members, so I just created a class with the needed members and just used toJson to create the json. If it's relevant to this question, then its inside an Android application.

Now I need to create a more complex json with many fields and several levels. An example of the json (at least a part of it just to show the "spirit" of it):

"sleep" : {
  "program" : {
   "appName" : "name",
   "appVersion" : "1.7"
   "serverVersion" : 19
   },
   "userType" : "new",
   "userInfo" : {
      "firstName" : "Hans",
      "lastName" : "Schmidt",
      "city" : "Berlin",
      "country" : "Germany",
    },
   "settings" : {
      "setting1" : "y",
      "setting2" : "none"
 }
 ...
}

In this case, do I need to create a different class for every tree? for example, a class for the "program" part, a class for the "userInfo" and so on and then create a class for the "sleep" root which contains every smaller class as its member and use toJson on it? I'm guessing it will work, but is it the most efficient way to create so many classes for a single Json?

Upvotes: 3

Views: 2289

Answers (3)

Davide Patti
Davide Patti

Reputation: 3471

You can use the Maps in order to achieve the goal. In the extreme case (I mean, in the case you don't want to create any classes), if you want to create this json:

{
   "sleep":{
      "userInfo":{
         "firstName":"Hans",
         "lastName":"Schmidt",
         "country":"Germany",
         "city":"Berlin"
      },
      "settings":{
         "setting2":"none",
         "setting1":"y"
      },
      "program":{
         "appVersion":"1.7",
         "serverVersion":19,
         "appName":"name"
      },
      "userType":"new"
   }
}

You could do:

    Gson gson = new Gson();

    Map<String, Object> finalObject= new HashMap<>();
    Map<String, Object> sleep= new HashMap<>();
    Map<String, Object> program= new HashMap<>();
    Map<String, String> userInfo= new HashMap<>();
    Map<String, Object> settings= new HashMap<>();

    program.put("appName", "name");
    program.put("appVersion", "1.7");
    program.put("serverVersion", 19);

    userInfo.put("firstName", "Hans");
    userInfo.put("lastName", "Schmidt");
    userInfo.put("city", "Berlin");
    userInfo.put("country", "Germany");


    settings.put("setting1", "y");
    settings.put("setting2", "none");

    sleep.put("program", program);
    sleep.put("userType", "new");
    sleep.put("userInfo", userInfo);
    sleep.put("settings", settings);

    finalObject.put("sleep", sleep);

    System.out.println(gson.toJson(finalObject));

But, as said in another answer, often it is recommended to create the POJOs.

EDIT

There is another way in order to do this. Using the JsonObject class:

    JsonObject finalJsonObject= new JsonObject();
    JsonObject jsonSleep= new JsonObject();
    JsonObject jsonProgram= new JsonObject();
    JsonObject jsonUserInfo= new JsonObject();
    JsonObject jsonSettings= new JsonObject();

    jsonUserInfo.addProperty("firstName", "Hans");
    jsonUserInfo.addProperty("lastName", "Schmidt");
    jsonUserInfo.addProperty("country", "Germany");
    jsonUserInfo.addProperty("city", "Berlin");


    jsonSettings.addProperty("setting2", "none");
    jsonSettings.addProperty("setting1", "y");

    jsonProgram.addProperty("appVersion", "1.7");
    jsonProgram.addProperty("serverVersion", 19);
    jsonProgram.addProperty("appName", "name");


    jsonSleep.add("userInfo", jsonUserInfo);
    jsonSleep.add("settings", jsonSettings);
    jsonSleep.add("program", jsonProgram);
    jsonSleep.addProperty("userType", "new");

    finalJsonObject.add("sleep", jsonSleep);

    System.out.println(String.valueOf(finalJsonObject));

If you notice that you use always the same code then you should create the classes (in order to improve the mapping and eliminate the repetition). If there are some classes that you use few times, you could use this approach (and avoid to create each classes that you need).

Upvotes: 0

Navankur Chauhan
Navankur Chauhan

Reputation: 417

You can achive this by creating the model classes and a parent class.

FOr example

Class Sleep{


hashmap<String,Object> sleep;

//getters and setters



}



Class program{
String appName,appVersion,serverVersion;

// getters and setters;


} 

Class userInfo{
String firstName,lastName,city,country

// getters and setters

}



Main(){

Sleep sleep = new Sleep();

Hashmap<String,Object> sl = new HashMap<>();
sleep.setSleep() = sl;

program p = new program();
p.setappName("name");
p.setappVersion("1.7");
p.serverVersion("19");

sl.put("program",p);

// similarly for the userInfo

new Gson().toJson(sleep);

// This will give you the nested json as you wanted.
}

Upvotes: 0

webo80
webo80

Reputation: 3403

You can take two approaches:

1) Create Java classes for each "level", and play with POJO fields. I think this is the correct approach. The GSON serializer is optimized for that, so don't worry about performance.

2) Create the JSON "by hand". This is not recommended, and you won't get any significant performance improvement. Also, you aren't using the power of the POO.

Anyway, if possible, try to organize your data to use as less "levels" as possible, this will definitely help with the performance.

Upvotes: 1

Related Questions