2017-07-24 32 views
0

您好,並提前感謝您。我一直在開發一個REST web服務,並且非常好。我決定使用json.simple庫來處理提交給Web服務的JSON函數,但我非常努力地使用JsonArray,我將它傳遞給下面的方法。該數組由一個或多個已在另一個類中拼湊在一起並傳入此方法的JSON對象組成。我在以前的json.simple版本的很多嘗試之後使用json.simple 2.1.2,並且正在從數組中獲取每個JsonObject。Java org.json.simple.JsonArray無法獲得JsonObjects

public createTransactions(JsonArray transArr){ 


for (int i = 0; i < transArr.size(); i++){ 

     try { 
      Object obj = transArr.get(i); //Works Fine 
      //but 
      JsonObject transJsonObj = (JsonObject)transArr.get(i); 
      //Doesn't work, the stack trace shows no error but this doesn't 
      // run (outside the try it stops execution again with the stack 
      // trace showing no error.) 

     } catch (Exception e){ 
      e.printStackTrace(); 
     } 
     System.out.println(transArr.toString()); 
     System.out.println(transArr.toJson()); 

     //both work output below* 

    } 

} 

輸出

* [{catalogue_id = 1,數量= 2,pickup_longitude = -1.4578941,pickup_latitude = 33.45548978},{catalogue_id = 2,數量= 3,pickup_longitude = -1.4578941,pickup_latitude = {「catalogue_id」:1,「qty」:2,「pickup pickup _長度」: - 1.4578941,「pickup海拔高度」:33.45548978){{catalogue_id = 1,qty = 4,pickup pickup長度= -1.4578941,pickup pickup海拔高度= 33.45548978}] },{ 「catalogue_id」:2 「數量」:3 「pickup_longitude」: - 1.4578941, 「pickup_latitude」:33.45548978},{ 「catalogue_id」:1, 「數量」:4 「pickup_longitude」: - 1.4578941,」 pickup _latitude「:33.45548978}]

無論我做什麼,代碼停止在這一點。我一直堅持這個晚上了。我可以在這個方法中手動構建JsonArray,並且這可以正常工作,並且可以遍歷它並分解每個JsonObject。當我用toString或toJson輸出手動構建的JsonArray時,輸出與上面相同,儘管順序不同。我已經用盡了所有可以在stackoverflow和google上找到的例子,所以我們不勝感激。

+0

它工作正常的我。 JsonArray的構建可能會傳入該方法。我的測試代碼:'JsonArray jsonArray = new JsonArray(); JSONObject obj = new JsonObject(); JsonObject obj = new JsonObject(); JSONObject obj = new JsonObject(); obj.put(「test」,「testVal」); obj.put(「testI」,new Integer(1)); JsonObject obj_1 = new JsonObject(); obj_1.put(「test」,「testVal」); obj_1.put(「testI」,new Integer(2)); \t \t \t \t jsonArray.add(obj); \t \t jsonArray.add(obj_1); \t \t \t \t createTransactions(jsonArray);' –

+0

謝謝,我想或許我可以在方法中創建一個。 Xxx –

回答

0

您可以使用一個迭代器,讓您的JSON對象

Iterator i = transArr.iterator(); 
JSONObject slide = i.next(); 
//do whatever you need 
+0

謝謝我也會放棄這一點。 –