如何在JSON字符串中检查给定对象是对象还是数组

我从网站获取JSON字符串。 我有这样的数据(JSON数组)

myconf= {URL:[blah,blah]} 

但有时这个数据可以是(JSON对象)

  myconf= {URL:{try}} 

也可以是空的

  myconf= {} 

我想在它的对象和不同的数组时做不同的操作。 直到我的代码,我试图只考虑数组,所以我得到以下exception。 但我无法检查对象或数组。

我得到以下exception

  org.json.JSONException: JSONObject["URL"] is not a JSONArray. 

任何人都可以建议如何修复它。 在这里,我知道对象和数组是JSON对象的实例。 但我找不到一个函数,我可以检查给定的实例是一个数组或对象。

我试过使用这个条件,但没有成功

 if ( myconf.length() == 0 ||myconf.has("URL")!=true||myconf.getJSONArray("URL").length()==0) 

JSON对象和数组分别是JSONObjectJSONArray实例。 JSONObjectJSONObject有一个get方法,它会返回一个对象,你可以检查你自己的类型而不用担心ClassCastExceptions,而且你去了。

 if (!json.isNull("URL")) { // Note, not `getJSONArray` or any of that. // This will give us whatever's at "URL", regardless of its type. Object item = json.get("URL"); // `instanceof` tells us whether the object can be cast to a specific type if (item instanceof JSONArray) { // it's an array JSONArray urlArray = (JSONArray) item; // do all kinds of JSONArray'ish things with urlArray } else { // if you know it's either an array or an object, then it's an object JSONObject urlObject = (JSONObject) item; // do objecty stuff with urlObject } } else { // URL is null/undefined // oh noes } 

有很多方法。

如果您担心系统资源问题/滥用Javaexception来确定数组或对象,则不建议使用此方法。

 try{ // codes to get JSON object } catch (JSONException e){ // codes to get JSON array } 

要么

这是推荐的。

 if (json instanceof Array) { // get JSON array } else { // get JSON object } 

我也遇到了同样的问题。 虽然,我已经很简单地修复了。

我的json如下:

 [{"id":5,"excerpt":"excerpt here"}, {"id":6,"excerpt":"another excerpt"}] 

有时,我得到的反应如下:

 {"id":7, "excerpt":"excerpt here"} 

我也像你一样得到了错误。 首先,我必须确定它是JSONObject还是JSONArray

JSON数组由[]覆盖,对象使用{}

所以,我添加了这段代码

 if(response.startWith("[")){ //JSON Array }else{ //JSON Object } 

这对我有用,我希望它对你也有帮助,因为它只是一个简单的方法

使用@Chao回答我可以解决我的问题。 其他方式我们也可以检查一下。

这是我的Json回复

 { "message": "Club Details.", "data": { "main": [ { "id": "47", "name": "Pizza", } ], "description": "description not found", "open_timings": "timings not found", "services": [ { "id": "1", "name": "Free Parking", "icon": "http:\/\/hoppyclub.com\/uploads\/services\/ic_free_parking.png" } ] } } 

现在,您可以像这样检查哪个对象是JSONObjectJSONArray作为响应。

 String response = "above is my reponse"; if (response != null && constant.isJSONValid(response)) { JSONObject jsonObject = new JSONObject(response); JSONObject dataJson = jsonObject.getJSONObject("data"); Object description = dataJson.get("description"); if (description instanceof String) { Log.e(TAG, "Description is JSONObject..........."); } else { Log.e(TAG, "Description is JSONArray..........."); } } 

这用于检查收到的json是否有效

 public boolean isJSONValid(String test) { try { new JSONObject(test); } catch (JSONException ex) { // eg in case JSONArray is valid as well... try { new JSONArray(test); } catch (JSONException ex1) { return false; } } return true; } 
Interesting Posts