2010-11-15 67 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