How To Get How Many Key Inside A Gson Object Model Class Android?
I have a response that will look like this: 'field_1':{ }, 'field_2' : { 'array_2': [ { ... all other fields }
Solution 1:
Try this...
try {
int total=0;
JSONObject json = newJSONObject(field_2);
Iterator<String> temp = json.keys();
while (temp.hasNext()) {
// do your other stuffs here
total=total+1; //at last you will get total objects in field_2
}
} catch (JSONException e) {
e.printStackTrace();
}
OR
JSONObjectobject = newJSONObject (field_2_jsonObject);
JSONArray keys = object.names ();
//KEYS SIZE WILL YOUR TOTAL LENGTH IN "field_2"for (int i = 0; i < keys.length (); i++) {
String key = keys.getString (i); // Here's your key
}
Hope this will work... :)
Solution 2:
lets say that your array object like this
publicclassMyObject {
@SerializedName("name")
@Expose
private String name;
@SerializedName("email")
@Expose
private String email;
// other getter and setter
}
so the parsing will be using Gson with retrofit like this
publicclassMyPojo {
@SerializedName("field_1")
@ExposeprivateField1 class1;
@SerializedName("field_2")
@ExposeprivateField2 class2;
@SerializedName("field_3")
@ExposeprivateField3 class3;
// other getter and setter
}
publicclassField2 {
privateMap<String,List<MyObject>> map=new HashMap<String, List<MyObject>>();
// other getter and setter
}
so the point here is that you don't know how many keys will be like array_1,array_2, ... etc , so you use a map of string which is the key , and the value is your json Object
Post a Comment for "How To Get How Many Key Inside A Gson Object Model Class Android?"