繁体   English   中英

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

[英]How to check whether the given object is object or Array in JSON string

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

 myconf= {URL:[blah,blah]}

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

 myconf= {URL:{try}}

也可以为空

 myconf= {}    

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

我收到以下异常

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

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

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

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

JSON 对象和数组分别是JSONObjectJSONArray实例。 此外, JSONObject有一个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
}

好几种方式。

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

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.startsWith("[")) {
  //JSON Array
} else {
  //JSON Object 
}

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

在此处查看有关 String.startsWith 的更多信息 - https://www.w3schools.com/java/ref_string_startswith.asp

使用@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) {
            // e.g. in case JSONArray is valid as well...
            try {
                new JSONArray(test);
            } catch (JSONException ex1) {
                return false;
            }
        }
        return true;
    }

下面使用 jackson api 的示例代码可用于始终获取 json 字符串作为 java 列表。 适用于数组 json 字符串和单个对象 json 字符串。

导入 com.fasterxml.jackson.databind.ObjectMapper;

public class JsonDataHandler {
    public List<MyBeanClass> createJsonObjectList(String jsonString) throws JsonMappingException, JsonProcessingException {
        ObjectMapper objMapper = new ObjectMapper();
        objMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        List<MyBeanClass> jsonObjectList = objMapper.readValue(jsonString, new TypeReference<List<MyBeanClass>>(){});
        return jsonObjectList;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM