开发者

JSONException: Misplaced object

开发者 https://www.devze.com 2023-01-24 22:16 出处:网络
This is my code: JSONStringer result = new JSONStringer(); for (long i = start; i <= end; i = i + day) {

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.


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号