Search code examples
javaandroidjsonjsonparser

Iterating/Getting JSONObject inside of JSONArray without key


Need to get the Every JSONObject inside this JSONArray. Currently there is only 2 JSONObjects are there but there will be more in the future. So, i need to make it dynamic based on length of the JSONArray.

Here is the whole JSON:

{
  "data": [
    {
      "previous_class_percentage": 58.0,
      "speech_disabilty": true,
      "hearing_difficulty": false,
      "last_name": "Krishnana",
      "weight": 54.0,
      "submitted_timestamp": "2018-02-15T10:22:00Z",
      "id_number": "VS017BH0004"
    },
    {
      "previous_class_percentage": 88.0,
      "speech_disabilty": true,
      "hearing_difficulty": false,
      "last_name": "Krishnana",
      "weight": 54.0,
      "submitted_timestamp": "2018-02-14T10:22:00Z",
      "id_number": "VS017BH0006"
    }
  ]
}

I am trying something like this

  try {
                        int k = 0;
                        while (i<sectionJsonArr.length()){
                            JSONObject data = sectionJsonArr.optJSONObject(k);
                            Log.d("json-array",data+"");
                            String b_certificate_no = data.getString("id_number");
                            if (student_birth_certfct_number.equals(b_certificate_no)){
                                Log.d("text","inside if");
                                //TO-DO CODE
                            }
                            k++;
                        }
                    }catch (JSONException e){
                        e.printStackTrace();
                    }

Solution

  • try{
        for( int i=0; i < sectionJsonArr.length(); i++){
          JSONObject data = obj.optJSONObject(i);
          Log.d("json-array",data+"");
          String b_certificate_no = data.getString("id_number");
          if (student_birth_certfct_number.equals(b_certificate_no)){
             Log.d("text","inside if");
                 //TO-DO CODE
          }
        }
    }catch(JSONException e){
      e.printStackTrace();
    }
    

    this is also a way to do that