0

我来自服务器的 JSON 响应随着用户输入而变化,假设在服务器上当用户添加一个项目时我得到响应为 JSONObject 但当项目超过 1 时响应是 JSONArray 形式。

现在如何处理这些响应以使我的应用程序不被杀死,需要使用检查点吗?

如果有两个项目..

"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":{

        }
     }

} }

4

1 回答 1

0

我认为您可以使用 optJSONArray("") 或 optJSONObject(""),它不会引发任何异常,但如果对象的类型不正确,则返回 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 ...]
}
于 2012-05-07T13:44:55.703 回答