[英]Checking whether an object is real JSONArray or JSONObject in Android/Java
我進行了一些研究,發現了這兩種檢查方法,但是我不知道哪一種檢查速度會更慢並且會導致更多的開銷?
方法1:
public boolean isJSONValid(String test)
{
try {
new JSONObject(test);
return true;
} catch(JSONException ex) {
return false;
}
}
方法2:
if (Law.get("LawSet") instanceof JSONObject)
{
JSONObject Lawset = Law.getJSONObject("LawSet");
}
else if (Law.get("LawSet") instanceof JSONArray)
{
JSONArray Lawset = Law.getJSONArray("LawSet");
}
編輯:顯然,這兩種方法都不會根據我在此問題下得到的評論起作用,因此,如何檢查傳入的字符串是有效的JSONObject還是JSONArray?
嘗試這個。
String myData= "{ ... }";
Object json = new JSONTokener(myData).nextValue();
if (json instanceof JSONObject)
//This is object
else if (json instanceof JSONArray)
//This is array
會很好的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.