这是我的代码:
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();
}
然后我得到一个JSONException。我还尝试使用不同的try-catch块创建和结束对象,如下所示:
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();
}
并在for循环中创建和结束JSONStringer,如下所示:
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();
}
我做错了什么?
感谢。
答案 0 :(得分:1)
您需要使用数组:
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();
}