How can I get the value on a position from a JSON Response on Android Studio?

60 Views Asked by At

I want to get the value of a specific object from this response, but I still don't understand at all the rules of the hierarchy.

The values I want are :

"F0092_AN8": 258523

and

"records": 1

This is the Json body that I'm working:

{
  "ServiceRequest1": {
    "fs_DATABROWSE_F0092": {
      "title": "Data Browser - F0092 [Library Lists - User]",
      "data": {
        "gridData": {
          "id": 52,
          "fullGridId": "52",
          "columns": {
            "F0092_AN8": "Address Number"
          },
          "rowset": [
            {
              "F0092_AN8": 258523
            }
          ],
          "summary": {
            "records": 1,
            "moreRecords": false
          }
        }
      },
      "errors": [],
      "warnings": []
    },
    "currentApp": "DATABROWSE_F0092",
    "timeStamp": "2023-05-16:16.05.23",
    "sysErrors": []
  }
}

I try to use this code on the response but can't reach the objects, and gives me an error:

JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.POST, Url.ROOT_URL, obj,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        progressDialog.dismiss();
                        Log.d("JSON response -->", response.toString());
                        try {
                            if (response.getJSONObject("fs_DATABROWSE_F0092").has("F0092_AN8")) {

Hope you guys can help me. Thx!

1

There are 1 best solutions below

1
S-Sh On BEST ANSWER

The JSON has hierarchical structure, so you should deep down to the tree step-by-step:

1.

JSONArray rowset = response.getJSONObject("ServiceRequest1")
  .getJSONObject("fs_DATABROWSE_F0092")
  .getJSONObject("data")
  .getJSONObject("gridData")
  .getJSONArray("rowset");
JSONObject row = rowset.getJSONObject(0);

Now, row contains

{
   "F0092_AN8": 258523
}
  1. Similarly, for records count:
JSONObject summary = response.getJSONObject("ServiceRequest1")
  .getJSONObject("fs_DATABROWSE_F0092")
  .getJSONObject("data")
  .getJSONObject("gridData")
  .getJSONObject("summary");
int count = summary.getInt("records");
  1. Of courde, you should check if any key exists and handle its absense in appropriate way.