Search code examples
javajsonjsonexception

JSONObject["keyName"] not found exception while parsing Json data even if key is present


I have a code which returns JSON data. I need to pick certain values from it but it throws Exception for some keys while some are successful.

Here is the JSON data

{"value":[{"Name":"abc.txt","DateTimeLastModified":"2017-09-21T20:11:04Z","IsInline":false,"ContentBytes":"some byte data","IsContactPhoto":false}]}

Here is how I am trying to pick the values from it

JSONObject jsonObject = response.getBody().getObject();
    JSONArray tsmresponse = (JSONArray) jsonObject.get("value");
    for(int i=0; i<tsmresponse.length(); i++){
        System.out.println("Name:: "+tsmresponse.getJSONObject(i).getString("Name"));           
            }

The code throws Exception org.json.JSONException: JSONObject["Name"] not found. while it is able to read DateTimeLastModified value.

Please help me to resolve this issue.


Solution

  • this should work for you, modify your code as follow:

    JSONObject jsonObject = response.getBody().getObject();
    JSONArray tsmresponse = jsonObject.getJSONArray("value");//here is your modification
    for(int i=0; i<tsmresponse.length(); i++){
        System.out.println("Name:: "+tsmresponse.getJSONObject(i).getString("Name"));           
            }
    

    try it and confirm me if this works