测试它是JSONObject还是JSONArray

时间:2012-04-03 06:39:35

标签: java json

我有一个json流,可以是:

{"intervention":

    { 
      "id":"3",
              "subject":"dddd",
              "details":"dddd",
              "beginDate":"2012-03-08T00:00:00+01:00",
              "endDate":"2012-03-18T00:00:00+01:00",
              "campus":
                       { 
                         "id":"2",
                         "name":"paris"
                       }
    }
}

或类似

{"intervention":
            [{
              "id":"1",
              "subject":"android",
              "details":"test",
              "beginDate":"2012-03-26T00:00:00+02:00",
              "endDate":"2012-04-09T00:00:00+02:00",
              "campus":{
                        "id":"1",
                        "name":"lille"
                       }
            },

    {
     "id":"2",
             "subject":"lozlzozlo",
             "details":"xxx",
             "beginDate":"2012-03-14T00:00:00+01:00",
             "endDate":"2012-03-18T00:00:00+01:00",
             "campus":{
                       "id":"1",
                       "name":"lille"
                      }
            }]
}   

在我的Java代码中,我执行以下操作:

JSONObject json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream     
JSONArray  interventionJsonArray = json.getJSONArray("intervention");

在第一种情况下,上述方法不起作用,因为流中只有一个元素。 如何检查流是object还是array

我尝试使用json.length(),但它没有用。

由于

7 个答案:

答案 0 :(得分:112)

这样的事情应该这样做:

JSONObject json;
Object     intervention;
JSONArray  interventionJsonArray;
JSONObject interventionObject;

json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream     
Object intervention = json.get("intervention");
if (intervention instanceof JSONArray) {
    // It's an array
    interventionJsonArray = (JSONArray)intervention;
}
else if (intervention instanceof JSONObject) {
    // It's an object
    interventionObject = (JSONObject)intervention;
}
else {
    // It's something else, like a string or number
}

这样做的好处是只需从主JSONObject获取属性值一次。由于获取属性值涉及遍历哈希树或类似物,这对于性能(对于它的价值)是有用的。

答案 1 :(得分:13)

也许像这样的支票?

JSONObject intervention = json.optJSONObject("intervention");

如果干预对象不是JSON对象,则返回JSONObjectnull。接下来,执行此操作:

JSONArray interventions;
if(intervention == null)
        interventions=jsonObject.optJSONArray("intervention");

如果数组是有效的JSONArray,则会返回一个数组,否则会返回null

答案 2 :(得分:9)

为简单起见,您只需从服务器结果中检查第一个字符串即可。

String result = EntityUtils.toString(httpResponse.getEntity()); //this function produce JSON
String firstChar = String.valueOf(result.charAt(0));

if (firstChar.equalsIgnoreCase("[")) {
    //json array
}else{
    //json object
}

这个技巧仅基于JSON格式的字符串{foo : "bar"}(对象) 或[ {foo : "bar"}, {foo: "bar2"} ](数组)

答案 3 :(得分:2)

      Object valueObj = uiJSON.get(keyValue);
        if (valueObj instanceof JSONObject) {
            this.parseJSON((JSONObject) valueObj);
        } else if (valueObj instanceof JSONArray) {
            this.parseJSONArray((JSONArray) valueObj);
        } else if(keyValue.equalsIgnoreCase("type")) {
            this.addFlagKey((String) valueObj);
        }

// ITETER JSONARRAY     私人void parseJSONArray(JSONArray jsonArray)抛出JSONException {         for(迭代器iterator = jsonArray.iterator(); iterator.hasNext();){             JSONObject对象=(JSONObject)iterator.next();             this.parseJSON(object);         }     }

答案 4 :(得分:0)

我没有尝试过,但也许......


JsonObject jRoot = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream
JsonElement interventionElement = jRoot.get("intervention");
JsonArray interventionList = new JsonArray();

if(interventionElement.isJsonArray()) interventionList.addAll(interventionElement.getAsJsonArray());
else interventionList.add(interventionElement);

如果它是JsonArray对象,只需使用getAsJsonArray()来强制转换它。如果没有,它只是一个元素,所以只需添加它。

无论如何,你的第一个例子坏了,你应该要求服务器的所有者修复它。 JSON数据结构必须一致。这不仅仅是因为有时干预只有一个元素,它不需要是一个数组。如果它只有1个元素,它将只是一个元素的数组,但仍然必须是一个数组,以便客户端可以使用始终相同的模式解析它。

答案 5 :(得分:0)

    //returns boolean as true if it is JSONObject else returns boolean false 
public static boolean returnBooleanBasedOnJsonObject(Object jsonVal){
        boolean h = false;
        try {
            JSONObject j1=(JSONObject)jsonVal;
            h=true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
   if(e.toString().contains("org.json.simple.JSONArray cannot be cast to     org.json.simple.JSONObject")){
                h=false;
            }
        }
        return h;

    }

答案 6 :(得分:0)

您可以使用以下代码获取输入字符串的对象。

String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
 //do something for JSONObject
else if (json instanceof JSONArray)
 //do something for JSONArray

链接:https://developer.android.com/reference/org/json/JSONTokener#nextValue

相关问题