ravi
ravi

Reputation: 6328

Dynamic model creation for JSON parsing using GSON in java

To parse the response from SOAP services I am using GSON. Currently I am having individual model classes for each service. There are tow services which are almost similar in response.

  1. Response from Service 1

{

   "settings":[
      {
         "type":"userPreferences",
         "enforced":false,
         "name":"SavedItems",
         "private":false,
         "value":{
            "type":"xs:string",
            "$":"sessionExpired"
         },
         "canWrite":true,
         "displayName":"Saved Items"
      }
   ]
}
  1. Response from Service 2

{

   "settings":[
      {
         "type":"selectMultipleItems",
         "enforced":true,
         "name":"cartInfo",
         "private":true,
         "value":{
            "type":"xs:string",
            "$":"currentPage"
         },
         "lookupValue": "Profile,Home,Transaction,Error",
         "canWrite":true,
         "displayName":"Current Page Index"
      }
   ]
}

Clearly visible there is one more filed i.e. lookupValue in the response from service 2.

I am having two questions here, which are listed below-

  1. Is the any way to handle this condition in a common model class rather than having individual model classes for each one?

  2. JSON is key value pair structure, can i create such class which can dynamically allocate each key mapped with its value? This will work for any JSON.

Upvotes: 0

Views: 1256

Answers (1)

PomPom
PomPom

Reputation: 1478

1 - You are not forced to provide each fields of the destination Object in your JSon. That means you can create an object with a lookupValue field, and use that same object for both Json above. The field will simply be ignored (null) in the first one.

2 - that's more or less what's Gson does internally. Try this :

public class Test {
  String x;
  Integer y;

  public static void main(String[] args) {
    Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Object.class, new JsonDeserializer<Object>() {
      @Override
      public Object deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
        Set<Entry<String, JsonElement>> values = arg0.getAsJsonObject().entrySet();
        System.out.println(values);

        return null;
      }

    }).create();

    gson.fromJson("{'x':'AA','y':5}", Test.class);
  }
}

As you see in the adapter, you can retrieve Set<Entry<String, JsonElement>> which provide you the name (in the Json) of a field and the associated value.

Upvotes: 2

Related Questions