2016-10-27 73 views
-1

我有一個來自我的CRM的API請求,如果只有一個結果,可以返回一個jsonObject,如果有多個結果,則返回一個jsonArray。以下是他們的樣子在JSON查看器如何解析Java中的jsonObject或Array

的JSONObject:

enter image description here

JsonArray:

enter image description here

在你回答之前,這不是我設計的,這是我CRM的設計,我沒有任何控制權,是的,我不喜歡它的設計。我沒有將記錄存儲在我自己的數據庫中並解析它的唯一原因是,我的帳戶存在問題,因爲我的帳戶沒有運行某些允許我自動添加記錄的工作流程。有什麼方法可以找出結果是使用java的對象還是數組?順便說一句,這是一個Android應用程序,我需要它來顯示手機上的記錄。

回答

0

你應該使用OPT命令,而不是GET

JSONObject potentialObject=response.getJsonObject("resuslt") 
.getJsonObject("Potentials"); 

// here use opt. if the object is null, it means its not the type you specified 
JSONObject row=potentialObject.optJsonObject("row"); 
if(row==null){ 
    // row is json array . 
    JSONArray rowArray=potentialObject.getJsonArray("row"); 
    // do whatever you like with rowArray 
} else { 
    // row is json object. do whatever you like with it 
} 
+0

完美!這是我正在尋找的。我試過的所有其他方法都會多次複製一條記錄。謝謝你的幫助。 –

-1

最簡單的方法是使用Moshi,以便即使在稍後更改模型的情況下也不必解析,您必須更改pojo並且它將起作用。

下面是自述

String json = ...; 

Moshi moshi = new Moshi.Builder().build(); 
JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class); 

BlackjackHand blackjackHand = jsonAdapter.fromJson(json); 
System.out.println(blackjackHand); 

https://github.com/square/moshi/blob/master/README.md

0

ONE

您可以使用關鍵字instanceof檢查情況作爲片斷

 if(json instanceof JSONObject){ 
      System.out.println("object"); 
     }else 
      System.out.println("array"); 

我認爲更好的方式來做到這一點是隻選擇JSONArray使用,使您的結果的格式可以預測和照顧。 JSONArray s可以包含JSONObject s。那就是他們可以覆蓋JSONObject的範圍。

例如,當您收到響應(在JSONObjectJSONArray中)時,您需要將其存儲在實例中。你打算存儲什麼樣的實例?所以爲了避免問題,使用JSONArray來存儲響應並提供語句來處理這個問題。

您也可以嘗試的方法在Java中重載泛型