How to write a Pojo using a dynamic key inside JSONarray

parse dynamic key json string using retrofit
how to handle dynamic json response in java
how to parse dynamic json in android

I don't even know if this is a valid question but I am having a hard time converting the API result to POJO since some key are dynamic.

{
"data": [{
        "something_edit": true
    },
    {
        "test_null": false
    }
],
"success": true

}

As you can see the key inside data are dynamic. I tried using jsonschema2pojo or other converter but it is declaring a named variable which is not a good result. BTW I am using retrofit and GSON library

EDIT:

So here is the flow, so the keys are the ones I asked on the API. So for Example I asked something_edit1, something_edit2 and something_edit3. The data result will be.

{

"data": [{
        "something_edit1": true
    }, {
        "something_edit2": false
    },
    {
        "something_edit3": false
    }
],

"success": true
}

You can use Json Object or Generics for your condition.

Using Json Object you can check, if key is exist in your json.

if(yourJsonObject.hasOwnProperty('key_name')){
   // do your work here
}

Using Generic you have to check, if your Pojo have instance of the Pojo.

if(YourMainPOJO instanceOf YourChildPojo){
   // do your work here
}

Try to view only Generic part in this link.

JSON handling with org.json / Handling dynamic key for JSON , This is an example for how to handle dynamic key for response. Here A and B are dynamic for JSON response. Parsing json array to generic class using Gson. Creating Payload as POJO Classes: This is the widely used process in the industry. In real time, you will be creating POJO classes to convert your JSON into Java object. I would also recommend you create payload in this way if you are going to implement API Automation in your project. POJO stands for Plain Old Java Object. A Pojo class will

It's hard to determine or you have to declare all the possible fields in your POJO or write your own json parser extending the Gson Parser or use a JsonElement which can be converted into json array, object and primitive, based on that result you can convert back to some specific pojo.

   /**
 * this will convert the whole json into map which you can use to determine the json elements
 *
 * @param json
 */
private void getModelFromJson(JsonObject json) {
    Gson gson = new Gson();
    Map<String, JsonElement> jsonElementMap = gson.fromJson(json.toString(), new TypeToken<Map<String, JsonElement>>() {
    }.getType());
    for (Map.Entry<String, JsonElement> jsonElementEntry : jsonElementMap.entrySet()) {
        if (jsonElementEntry.getValue().isJsonPrimitive()) {
            //json primitives are data types, do something
            //get json boolean
            //you can here also check if json element has some json object or json array or primitives based on that
            //you can convert this to something else after comparison
            if (true) {
                InterestModelResponse response = gson.fromJson(jsonElementEntry.getValue().getAsJsonObject().toString(), InterestModelResponse.class);
                //use your dynamic converted model
            }
        } else {
            //do something else
        }
    }

}

Dynamic deserialization API response using Gson, We can reduce the POJO classes using the Generic concept of Java and Gson. Now we check with JSON Array response inside result key of For above examples, we can reuse almost all common classes except the  It is used for reading and writing JSON among other tasks. Using Jackson, you can easily handle automatic conversion from Java objects to JSON and back. In this article, we delve into some common Jackson usage patterns. 2. Converting a POJO to JSON. Suppose we want to convert a sample POJO (Plain Old Java Object) to JSON.

2 Years ago we did a project in which we had to handle notifications data with different type of objects in same array we handle that while using retrofit

this is our retrofit Creator class

class Creator {
    public static FullTeamService newFullTeamService() {
        final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        final OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();

        final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(FullTeamService.HOST)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(GsonUtils.get()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(FullTeamService.class);
    }
}

and GsonUtils.java is:

public class GsonUtils {
    private static final Gson sGson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
        .registerTypeAdapter(NotificationObject.class, new NotificationDeserializer())
        .create();

   private GsonUtils() {}

   public static Gson get() {
    return sGson;
   }
}

NotificationObject is something like:

public class NotificationObject {

@SerializedName("ID")
@Expose
private long ID;

@SerializedName("type")
@Expose
private Type type;

@SerializedName("DataObject")
@Expose
private NotificationDataObject dataObject;

public void setDataObject(NotificationDataObject newsFields) {
    dataObject = newsFields;
}

@SuppressWarnings("unchecked")
public <T> T getDataObject() {
    return (T) dataObject;
}
public enum Type {
    @SerializedName("0")
    CHAT_MESSAGE,
    @SerializedName("10")
    GAME_APPLICATION,
    @SerializedName("20")
    GAME_APPLICATION_RESPONSE,
    @SerializedName("30")
    GAME_INVITE....
}
}

NotificationDataObject as new class is like:

public class NotificationDataObject {}

and finally NotificationDeserializer is like:

public class NotificationDeserializer implements JsonDeserializer<NotificationObject> {
@Override
public NotificationObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    final JsonObject itemBean = json.getAsJsonObject();
    final NotificationObject object = GsonUtils.getSimpleGson().fromJson(itemBean, NotificationObject.class);
    switch (object.getType()) {
        case CHAT_MESSAGE:
            break;
        case GAME_APPLICATION:
            object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
                    GameApplicationNotification.class));
            break;
        case GAME_APPLICATION_RESPONSE:
            object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
                    GameApplicationResponseNotification.class));
            break;
        case GAME_INVITE:
            object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
                    GameInviteNotification.class));
            break;
}
    return object;
}
}

Happy coding ...!

any query will be appreciated...

Using gson to parse a json with dynamic key and value in java, The following two examples demonstrate, first with an array, then with an object: Parse Json Object with dynamic keys using Gson while (it. How is it possible to get all the keys in the JSON through iteration using GSON or JsonObject. You can convert JSON String to Java object in just 2 lines by using Gson as shown  A Json array is an ordered collection of values that are enclosed in square brackets i.e. it begins with ‘[’ and ends with ‘]’. The values in the arrays are separated by ‘,’ (comma).

org.json.JSONObject.keys java code examples, next(); // get the value of the dynamic key JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey); // do something here with the​  It could either be a JsonObject, a JsonArray, a JsonPrimitive, or a JsonNull. Gson tree model write In the following example, we use the Gson tree model API to write Java objects into JSON.

Mapping a Dynamic JSON Object with Jackson, Explore multiple ways of handling dynamic JSON objects with Jackson. multiple ways of mapping dynamic JSON objects into Java classes. have a field objectMapper of type com.fasterxml.jackson.databind. We can map the common properties with the following Java class: ? details.put(key, value);. If you have JSON that you want to map into a POJO without writing the full POJO class, then you can make use of the jsonschema2pojo library.This is an excellent library that can create Java

Get dynamic Key and value from json file, I'm a Talend developer and i have a json files that contain a dynamic part and because i can't get the keys so i change to create a java class to get the keys. keys (ena and nature) and the others keys are dynamic like this example. object printJSON((JSONObject) valObj); } else { // print key-value pair  We hope you know the drill now. First, we've to write an appropriate model for the JSON response. We can re-use our Founder class from the previous section: public class GeneralInfo { String name; String website; List<Founder> founders; } The advantage of the list nested in an object is the simple Gson call without any TypeToken handling. We

Comments
  • what i understand from your question. the keys inside data are dynamic like you get the key "something_edit" sometime and sometimes you get the key "test_null" and sometimes both. my question is the keys are getting are confirm like is this confirm that name of the key will be same and will defenetly get some key??
  • is your data variables are predefined or will be declared new any time? like I wrote code for an app in which I got array list of different objects ... so I parsed them by detecting type... so if you have that case then I can help you....
  • @sourabhkaushik yes for your question sometimes the values on data might change based on my request. For example I requested something_edit1, something_edit2, something_edit3 then the data result should be "data": [{"something_edit1": true}, {"something_edit2": false}, {"something_edit3": false}]
  • @Hanzala please see the Edit
  • stackoverflow.com/questions/43255577/…
  • Hi actually I am using retrofit and it will return the Pojo class with data in it thats why I need the pojo to handle it. I get your point that it is easier to just get the response String and modify it based on my requirements. Thanks
  • @Androyds retrofit return json also. If you want help let me know. I think it might be difficult to handle this dynamic POJO using Objects.
  • I guess for now its either using the response String,create pojo based on response or adding all the keys on POJO. Thanks for clarification.