theTuxRacer
theTuxRacer

Reputation: 13869

JSONException: Misplaced object

This is my code:

    JSONStringer result = new JSONStringer();

    for (long i = start; i <= end; i = i + day) {
        ttm.put("$gte", "" + i);
        ttm.put("$lte", "" + (i + day));
        //code code code

        int count = statisticCollection.find(query).count();

        try {
            result.object().key("ttm").value(i).key("count").value(count);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        result.endObject();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I then get a JSONException. I also tried creating and ending the object with a different try-catch block, as below:

    JSONStringer result = new JSONStringer();

    try {
        result.object();
    } catch (Exception e) {
        e.printStackTrace();
    }

    for (long i = start; i <= end; i = i + day) {
        ttm.put("$gte", "" + i);
        ttm.put("$lte", "" + (i + day));

        //code code code

        long count = statisticCollection.find(query).count();

        try {
            result.key("ttm").value(i).key("count").value(count);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        result.endObject();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

and creating and ending the JSONStringer in the for loop itself, as follows:

JSONStringer result = new JSONStringer();

for (long i = start; i <= end; i = i + day) {
    ttm.put("$gte", "" + i);
    ttm.put("$lte", "" + (i + day));
    //code code code

    int count = statisticCollection.find(query).count();

try {
     result.object().key("ttm").value(i).key("count").value(count).endObject();
} catch (JSONException e) {
            e.printStackTrace();
  }

What am I doing wrong?

Thanks.

Upvotes: 1

Views: 6223

Answers (1)

dogbane
dogbane

Reputation: 274522

You need to use an array:

JSONStringer result = new JSONStringer();
JSONWriter array = result.array();

for (long i = start; i <= end; i = i + day) {
    ttm.put("$gte", "" + i);
    ttm.put("$lte", "" + (i + day));
    //code code code

    int count = statisticCollection.find(query).count();

    try {
        array.object().key("ttm").value(i).key("count").value(count).endObject();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

try {
    array.endArray();
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Upvotes: 1

Related Questions