2012-05-07 17 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 ...] 
}