2013-12-11 118 views
0

你好,我叫一個服務,如果它包含多個對象,它使列表,但是當它僅包含一個對象時,它返回一個對象不是[]缺少一個列表,其實我想將它們轉換成Java使用GSON但​​唯一例外的情況下,拋出異常,但是當它包含列表它做工精細其實我需要我的單身GSON字符串轉換爲數組類,請幫我..here是字符串轉換JSON字符串JSON數組

{ 
    "response":{ 
     "projects":{ 
     "project":{ 
      "ixWorkflow":1, 
      "sEmail":"[email protected]", 
      "sPhone":"", 
      "ixProject":2, 
      "ixPersonOwner":2, 
      "fDeleted":false, 
      "sProject":"Project Default", 
      "fInbox":true, 
      "sPersonOwner":"junaid" 
     } 
     } 
    } 
} 

我想它就像

{ 
    "response":{ 
     "projects":{ 
     "project":[ 
      { 
       "ixWorkflow":1, 
       "sEmail":"[email protected]", 
       "sPhone":"", 
       "ixProject":6, 
       "ixPersonOwner":2, 
       "fDeleted":false, 
       "sProject":"project 2", 
       "fInbox":false, 
       "sPersonOwner":"junaid" 
      }, 
      { 
       "ixWorkflow":1, 
       "sEmail":"[email protected]", 
       "sPhone":"", 
       "ixProject":2, 
       "ixPersonOwner":2, 
       "fDeleted":false, 
       "sProject":"Project Default", 
       "fInbox":true, 
       "sPersonOwner":"junaid" 
      } 
     ] 
     } 
    } 
} 
+4

請添加更多的 '句號' 你的問題。這看起來更像是讀一本弗吉尼亞伍爾夫小說。 – aquaraga

+1

請包括您嘗試過的代碼。 – 2013-12-11 11:55:54

+0

你可以請包括你的解析代碼。 –

回答

1

參照t Øhttps://stackoverflow.com/a/7284813/1105291

請嘗試以下代碼,您通過JSON來GSON的對象轉換之前,並請讓你得到任何錯誤我知道。只有我能看到的可能性是if的例外。

JSONObject jsonObject = new JSONObject(responseString); 
    JSONObject projectsJsonObject = jsonObject.getJSONObject("response").getJSONObject("projects"); 
    if(projectsJsonObject.getJSONArray("project") == null) 
    { 
     JSONArray jsonArray = new JSONArray(); 
     jsonArray.put(projectsJsonObject.getJSONObject("project")); 
     projectsJsonObject.put("project", jsonArray); 

    } 
    //Pass jsonObject to Gson 
+0

JSONObject [「project」]不是JSONArr它拋出這個異常 –

+0

我用projectsJsonObject.optJSONArray(「project」)而不是projectsJsonObject.getJSONArray(「project」)== null反正休息很好,非常感謝很多 –

+0

@JunaidAkhtar I was期待異常但在其他地方,但我很高興它幫助:) –

0

使用Google Gson

JsonParser parser = new JsonParser(); 
JsonObject o = (JsonObject)parser.parse("{\"a\": \"A\"}");