Using GSon how to get multiple vaues from JSONObject

421 Views Asked by At

Hi the below is my response from format

object {6}
  csdfgi_fgid   :   4casdff9743a1-3f9asdf2-4
  fesdfgedVsdfgersionsfdg   :   7
  sdfg  :   28
  feesdfgdStart :   0
  fesdfedCsdfgoudfsgnt  :   28
  discover[28]
   0{4}
    DiscCat :   Tip
    templateCat{2}
        name    :   tip.tp
        version :   2
    timestamp   :   1421146871251
    content{1}

I am getting these values using Serializable in class like below

@SerializedName("csdfgi_fgid")
public String sCdfsisdfId;

@SerializedName("feedVersion")
public Long lFesdfgedVsdfgfsersdfsion;

@SerializedName("feed")
public ArrayList<DiscoverModel> discover;

Now in the array list again there is a Json Object "templateCat" which has two parameters "name , version". Now how to get values from this JSON Object

2

There are 2 best solutions below

0
On BEST ANSWER

First of all you need to assign all the JSONObject that you are getting in a POJO class. After that getting JSONObject(templateCat) from JSONArray(discover) you have to do looping. For example:

for(int i=0;i<discover.size();i++){

   TemplateCat templateCat = discover.get(i).getTemplateCat();
   String strName = templateCat.getName();
   String strVersion = templateCat.getVersion();

  //If you want to get all name and version as list. Add strName and strVersion to ArrayList. <br>

    For Example :  nameArray.add(strName);
                   versionArray.add(strVersion);
}
0
On

You'll have to get that JSON array first, iterate thru it and then use Gson to convert it into your desired object.

JSONObject rootJson = /* Get your JSON object here */;
JSONArray nestedArray = rootJson.getJsonArray("your_nested_json_array_name");

List<YourObject> objects;
for(int i = 0; i < nestedArray.size(); i++) {
    String objectJsonString = nestedArray.get(i);
    YourObject o = new Gson().fromJson(objectJsonString, YourObject.class);

    objects.add(o);
}

..the last thing you'd need to do is to set our objects list to your desired instance.