47

I am in a bit of a fix regarding the JSONObject that I am getting as a response from the server.

jsonObj = new JSONObject(resultString);
            JSONObject sync_reponse = jsonObj.getJSONObject("syncresponse");
            String synckey_string = sync_reponse.getString("synckey");
            JSONArray createdtrs_array = sync_reponse.getJSONArray("createdtrs");
            JSONArray modtrs_array = sync_reponse.getJSONArray("modtrs");
            JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
            String deleted_string = deletedtrs_array.toString();

{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]

as you can see in the response that I am getting I am parsing the JSONObject and creating syncresponse, synckey as a JSON object createdtrs, modtrs, deletedtrs as a JSONArray. I want to access the JSONObject from deletedtrs, so that I can split them apart and use the values. i.e I want to extract companyid, username, date etc.

How can I go about this ?

Thanks for your input.

Vinoth
  • 1,339
  • 6
  • 23
  • 42

7 Answers7

132

JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:

JSONArray array;
for(int n = 0; n < array.length(); n++)
{
    JSONObject object = array.getJSONObject(n);
    // do some stuff....
}
Lars
  • 4,082
  • 2
  • 20
  • 20
  • @Lars I know this is already quite old, but for anyone who still needs this and comes here: wouldnt it be better (performance/memory-wise) to put `JSONObject object;` before the loop, and simply overwrite the existing object instead of possibly creating tons of temporary objects? – Benjamin Schwalb Jul 10 '13 at 08:20
  • @BenjaminSchwalb You're right, that would be better. I wrote it like this for readability and clarity, but when you implement it in your own code, your addition makes it more efficient – Lars Aug 02 '13 at 10:10
  • It shows error - cannot make static reference to non static method getJSONObject(int) from the type JSONArray. – Confuse Sep 06 '14 at 11:15
  • Replace the `JSONArray` with the name of your `JSONArray` object. For example `JSONArray array` means you type `JSONObject object = array.getJSONObject(n)` (The same goes for `JSONArray.length()`) – Lars Sep 08 '14 at 12:13
  • About what library are you talking about? JSONObject, OK, but from what library? – Karol Król Aug 29 '18 at 11:26
  • @KarolKról From any network request making library like retrofit in android. The response you get from the server, you can parse it like above. – Gunesh Shanbhag May 15 '21 at 04:23
23

Here is your json:

{
    "syncresponse": {
       "synckey": "2011-09-30 14:52:00",
        "createdtrs": [

        ],
        "modtrs": [

        ],
        "deletedtrs": [
          {
           "companyid": "UTB17",
           "username": "DA",
           "date": "2011-09-26",
           "reportid": "31341"
      }
       ]
   }
}

and it's parsing:

JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
   JSONObject object3 = jArray3.getJSONObject(i);
   String comp_id = object3.getString("companyid");
   String username = object3.getString("username");
   String date = object3.getString("date");
   String report_id = object3.getString("reportid");
}
Vineet Shukla
  • 23,865
  • 10
  • 55
  • 63
  • i have a question mark on your jsonarrat looping, why loop if another iteration will over write the previouse object3 hence the comp-id,username,date and report-id variables. – Samuel Owino Sep 11 '17 at 06:53
2
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");

for(int i = 0; deletedtrs_array.length(); i++){

            JSONObject myObj = deletedtrs_array.getJSONObject(i);
}
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
1

When using google gson library.

var getRowData =
[{
    "dayOfWeek": "Sun",
    "date": "11-Mar-2012",
    "los": "1",
    "specialEvent": "",
    "lrv": "0"
},
{
    "dayOfWeek": "Mon",
    "date": "",
    "los": "2",
    "specialEvent": "",
    "lrv": "0.16"
}];

    JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
     JsonArray  jsonArray = root.getAsJsonArray();
     JsonObject  jsonObject1 = jsonArray.get(0).getAsJsonObject();
     String dayOfWeek = jsonObject1.get("dayOfWeek").toString();

// when using jackson library

    JsonFactory f = new JsonFactory();
              ObjectMapper mapper = new ObjectMapper();
          JsonParser jp = f.createJsonParser(getRowData);
          // advance stream to START_ARRAY first:
          jp.nextToken();
          // and then each time, advance to opening START_OBJECT
         while (jp.nextToken() == JsonToken.START_OBJECT) {
            Map<String,Object> userData = mapper.readValue(jp, Map.class);
            userData.get("dayOfWeek");
            // process
           // after binding, stream points to closing END_OBJECT
        }
Arun Pratap Singh
  • 3,428
  • 30
  • 23
1
{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]

The get companyid, username, date;

jsonObj.syncresponse.deletedtrs[0].companyid
jsonObj.syncresponse.deletedtrs[0].username
jsonObj.syncresponse.deletedtrs[0].date
Orson
  • 14,981
  • 11
  • 56
  • 70
1

start from

JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");

you can iterate through JSONArray and use values directly or create Objects of your own type
which will handle data fields inside of each deletedtrs_array member

Iterating

for(int i = 0; i < deletedtrs_array.length(); i++){
    JSONObject obj = deletedtrs_array.getJSONObject(i);
    Log.d("Item no."+i, obj.toString());

    // create object of type DeletedTrsWrapper like this
    DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj);

    // String company_id = obj.getString("companyid");
    // String username = obj.getString("username");
    // String date = obj.getString("date");
    // int report_id = obj.getInt("reportid");
}

Own object type

class DeletedTrsWrapper {

    public String company_id;
    public String username;
    public String date;
    public int report_id;

    public DeletedTrsWrapper(JSONObject obj){
        company_id = obj.getString("companyid");
        username = obj.getString("username");
        date = obj.getString("date");
        report_id = obj.getInt("reportid");
    }
}
Marek Sebera
  • 39,650
  • 37
  • 158
  • 244
  • hi, i have a doubt about json here what is value of var. result in this line `JSONObject object = new JSONObject(result);` i am new to this .even a link about parsing json will help me thank u – jasinth premkumar Jul 17 '18 at 14:05
0

Make use of Android Volly library as much as possible. It maps your JSON reponse in respective class objects. You can add getter setter for that response model objects. And then you can access these JSON values/parameter using .operator like normal JAVA Object. It makes response handling very simple.

snehal_penurkar
  • 273
  • 1
  • 3
  • 15