-2

I am fetching Json data from url and the data is in this format.

{
"Android": {
"candidate": [
  {
    "id": "2466965",
    "candidate_name": "Surajit  Ray"
  },
  {
    "id": "2468313",
    "candidate_name": "Ankit  Dixit"
  }
]
}
}

i want to parse this json data and i am using this technique to do so.

 try {

              //  ***** Creates a new JSONObject with name/value mappings from the JSON string. *******
                jsonResponse = new JSONObject(Content);

            //    **** Returns the value mapped by name if it exists and is a JSONArray. **
            //    ******  Returns null otherwise.  ******
                JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");
                //JSONArray jsonMainNode=   jsonResponse.getJSONArray("Android").getJSONObject(0).getJSONArray("candidate");
                //   ********** Process each JSON Node ***********

                int lengthJsonArr = jsonMainNode.length();

                System.out.println("length is " + lengthJsonArr);



                for(int i=0; i < lengthJsonArr; i++)
                {
                  //  ***** Get Object for each JSON node.**********
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                  //  ****** Fetch node values *********
                    String ide       = jsonChildNode.optString("id").toString();
                    String name       = jsonChildNode.optString("candidate_name").toString();
                    //String number     = jsonChildNode.optString("number").toString();
                    //String date_added = jsonChildNode.optString("date_added").toString();



                        OutputData +="id is"+ide+ " Name           : " + name;
                 /*   +" " + "Number      : "+ number +" "
                            + "Time                : "+ date_added +" " +"-------------------------------------------------- ";
       */
                    }

Toast.makeText(getApplicationContext(),"parsed data is "+OutputData,Toast.LENGTH_LONG).show();

but this is giving me error.please guide me as what are the various kind of json formats and how can we parse them in String.

1 Answers1

1

Your problem is that Android is not a JSONArray, it's an object. Use the corresponding method to get JsonObjects.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245