[java] Getting JSONObject from JSONArray

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.

This question is related to java android json

The answer is


{"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

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

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

            JSONObject myObj = deletedtrs_array.getJSONObject(i);
}

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");
}

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.


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
        }

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");
    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?