2012-05-07 18 views
0

我的JSON服務器響應是作爲用戶輸入更改,假設在服務器上時,當用戶添加一個項目,然後我得到響應作爲JSONObject,但是當項目超過1然後響應是在JSONArray形式。JSON響應改變爲沒有項目變化

現在如何處理這些響應,以便我的應用程序不會死亡,需要使用檢查點?

兩個項目的情況下

..

"items":{ 
    "item":[ 
      { 
      "item_id":"49623", 
      "type":"Products", 
      "name":"desktop app", 
      "description":"", 
      "unit_cost":"162.45", 
      "quantity":"1.00", 
      "discount":"0.00", 
      "discount_type":"Percent", 
      "tax1_percent":"0.00", 
      "tax2_percent":"0.00" 

     }, 
     { 
      "item_id":"52851", 
      "type":"Products", 
      "name":"", 
      "description":"", 
      "unit_cost":"5,290.50", 
      "quantity":"1.00", 
      "discount":"0.00", 
      "discount_type":"Percent", 
      "tax1_name":{ 

      }, 
      "tax1_percent":"0.00", 
      "tax1_type":{ 

      }, 
      "tax2_name":{ 

      }, 
      "tax2_percent":"0.00", 
      "tax2_type":{ 

      } 
     } 

] }

單項

"items":{ 
    "item":{ 
       "item_id":"49623", 
       "type":"Products", 
       "name":"desktop app", 
     "description":"this is the software for your desktop system sequerty", 
     "unit_cost":"162.45", 
     "quantity":"1.00", 
     "discount":"0.00", 
     "discount_type":"Percent", 
     "tax1_name":{ 

     }, 
     "tax1_percent":"0.00", 
     "tax1_type":{ 

     }, 
     "tax2_name":{ 

     }, 
     "tax2_percent":"0.00", 
     "tax2_type":{ 

     } 
    } 

}}

+0

什麼是您的應用程序上面兩種情況的當前行爲.. – Ronnie

回答

0

我想你可以使用optJSONArray的情況下, (「」)或optJSONObject(「」),它不會拋出任何異議eption,但如果對象不是正確的類型,則返回null。

JSONObject items = myJSON.getJSONObject("items"); 
Object item; 
if (items.optJSONArray("item") != null){ 
//The result isn't null so it is a JSONArray 
item = items.optJSONArray("item"); 
} 
else 
{ 
//The result is null so it isn't a JSONArray 
item = items.optJSONObject("item"); 
} 

然後,你只需要爲你想使用你的對象,使用「的instanceof」:

if (item instanceof JSONObject){ 
// The object is a JSONObject 
[... Your code ...] 
} 
else 
{ 
// The object is a JSONArray 
[... Your code ...] 
}