2012-05-07 10 views
0

JSONレスポンスがサーバーからユーザー入力として変更されました。ユーザーが1つのアイテムを追加したときにJSONObjectとしてレスポンスを返しましたが、アイテムが1以上の場合レスポンスはJSONArrayフォーム。JSONレスポンスがアイテムの変更なしで変更されました

私のアプリケーションが殺されないようにこれらの応答を処理する方法は、チェックポイントを使用する必要がありますか? 2つの項目の場合は

..

"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( "")で、excを投げないオブジェクトが正しい型にない場合は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」を使用して、あなたが望むように、あなたのオブジェクトを使用する必要があります:

上記の2つのシナリオのためのアプリの現在の行動は何
if (item instanceof JSONObject){ 
// The object is a JSONObject 
[... Your code ...] 
} 
else 
{ 
// The object is a JSONArray 
[... Your code ...] 
} 
関連する問題