2010-11-15 49 views
1

这是我的代码:JSONException:找不到对象

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

异常消息(也可能是行号)将有希望在工作出了问题是什么是有用的。现在它确实给出了更多的上下文,而不是“出错了”(从你的问题中已经清楚了)。 – 2010-11-15 09:34:23

+0

追踪粘贴在这里:http://pastebin.ca/1991983 – theTuxRacer 2010-11-15 09:41:02

回答

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

哇,那工作!你能告诉我我做错了什么吗?我看到你添加了一个JSONWriter。 – theTuxRacer 2010-11-15 10:10:14