【问题标题】:JSON Java check element is a JSONArray or JSONObjectJSON Java 检查元素是 JSONArray 或 JSONObject
【发布时间】:2011-11-09 05:23:09
【问题描述】:

如何检查一个元素是 JSONArray 还是 JSONObject。我写了代码来检查,

if(jsonObject.getJSONObject("Category").getClass().isArray()) {

} else {

}

在这种情况下,如果元素“类别”是 JSONObject,那么它可以正常工作,但如果它包含一个数组,那么它会抛出异常:JSONArray 无法转换为 JSONObject。请帮忙。 谢谢。

【问题讨论】:

标签: java android web-services json


【解决方案1】:

是的,这是因为 getJSONObject("category") 会尝试将 String 转换为 JSONObject,这将引发 JSONException。您应该执行以下操作:

使用以下方法检查该对象是否为JSONObject

   JSONObject category=jsonObject.optJSONObject("Category");

如果 category 对象不是 json 对象,它将返回 JSONObjectnull。 然后执行以下操作:

   JSONArray categories;
   if(category == null)
        categories=jsonObject.optJSONArray("Category");

这将返回您的 JSONArray 或 null 如果它不是有效的 JSONArray

【讨论】:

    【解决方案2】:

    即使你得到了你的答案,但它仍然可以帮助其他用户......

     if (Law.get("LawSet") instanceof JSONObject)
     {
        JSONObject Lawset = Law.getJSONObject("LawSet");                        
     }
     else if (Law.get("LawSet") instanceof JSONArray)
    {
        JSONArray Lawset = Law.getJSONArray("LawSet");
    }
    

    这里Law 是其他JSONObjectLawSet 是您要查找的密钥JSONObject or JSONArray

    【讨论】:

    • 非常感谢我应该在对象和数组之间进行验证.. 所以得到了解决方案!!!!!! :)
    • 哇...拯救了我的一天...谢谢@Vikas。
    【解决方案3】:
    String data = "{ ... }";
    Object json = new JSONTokener(data).nextValue();
    if (json instanceof JSONObject)
      //you have an object
    else if (json instanceof JSONArray)
      //you have an array
    

    tokenizer 能够返回更多类型:http://developer.android.com/reference/org/json/JSONTokener.html#nextValue()

    【讨论】:

      【解决方案4】:
                 if (element instanceof JSONObject) {
      
                      Map<String, Object> map = json2Java.getMap(element
                              .toString());
                      if (logger.isDebugEnabled()) {
                          logger.debug("Key=" + key + " JSONObject, Values="
                                  + element);
                      }
                      for (Entry<String, Object> entry : map.entrySet()) {
                          if (logger.isDebugEnabled()) {
                              logger.debug(entry.getKey() + "/"
                                      + entry.getValue());
                          }
                          jsonMap.put(entry.getKey(), entry.getValue());
                      }
                  }
      

      【讨论】:

        【解决方案5】:

        您可以使用instanceof 来检查您获得的结果的类型。然后你就可以随心所欲地处理了。

        【讨论】:

          猜你喜欢
          • 2011-09-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多