Modulus Modulus - 3 years ago 335
JSON Question

JSONException: JSONObject not found

So I wrote a program that connects to an API endpoint that gives me a dictionary consisting of a date and a # of seconds to add to that date:


I want to add those seconds to the date and return it to the API. My getDate() from the dictionary works fine but my getSeconds() is throwing a

JSONException: JSONObject ["{\"datestamp\":\"2016-11-22T20:46:38Z\",\"interval\":209836}"] not found.

Here is my getSeconds():

private static String getSeconds(String retrievedJson) throws JSONException, IOException {

JSONObject jsonTime = new JSONObject(retrievedJson);
String interval = jsonTime.getString("interval"); <-- if I do it this way I get this exception org.json.JSONException: JSONObject["interval"] not a string.
String interval = jsonTime.getJSONObject(retrievedJson).getString("interval"); <--- and if I do it this way it get the JSONException: JSONObject not found exception
return interval;

Here's how I'm calling it..

public void request() throws JSONException, IOException {

String retrievedJson = receiveInfo();
if (retrievedJson != null){
String finalTime = getFinalTime(retrievedJson);

and here's my getFinalTime():

private static String getFinalTime(String retrievedJson) throws JSONException, IOException {
String gotDateStamp = getDate(retrievedJson);
String gotInterval = getSeconds(retrievedJson);

String finalTime = addSecondsToDate(gotDateStamp, gotInterval);
return finalTime;


I've been working on this exception all day and can't seem to figure it out.

Answer Source

Here, you go:


import org.json.JSONException;
import org.json.JSONObject;

public class JsonParsing {

     * @param args
     * @throws JSONException 
    public static void main(String[] args) throws JSONException {

        String retrievedJson= "{\"datestamp\":\"2016-11-22T20:46:38Z\",\"interval\":209836}";
        JSONObject jsonTime = new JSONObject(retrievedJson);
        Long interval = jsonTime.getLong("interval");
        System.out.println("Main Json Data : " + interval);

        String retrievedJson2 = "{\"datestamp\":\"2016-11-22T20:46:38Z\",\"interval\":209836,inner:{\"datestamp\":\"2016-11-22T20:46:38Z\",\"interval\":209837}}";
        JSONObject jsonTime2 = new JSONObject(retrievedJson2);
        String interval2 = jsonTime2.getJSONObject("inner").getString("interval");
        System.out.println("Inner Json Data : "+ interval2);
        //String interval1 = jsonTime. //<--- and if I do it this way it get the JSONException: JSONObject not found exception




getJSONObject method return a inner Json object. In your case interval is just a Long variable not a Json object. I have created an example Json object with a nested Json and demonstrated the usage of getJSONObject.

I hope, It will give you some kind of insight.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download