![](/img/trans.png)
[英]How do I detect if an embedded JSON element is a JSONObject or JSONArray in Java
[英]JSON Java check element is a JSONArray or JSONObject
如何檢查元素是JSONArray還是JSONObject。 我寫了代碼來檢查,
if(jsonObject.getJSONObject("Category").getClass().isArray()) {
} else {
}
在這種情況下,如果元素'category'是JSONObject,那么它工作正常,但如果它包含一個數組,那么它會拋出異常:JSONArray無法轉換為JSONObject。 請幫忙。 謝謝。
是的,這是因為getJSONObject("category")
將嘗試將該String
轉換為JSONObject,這會拋出JSONException
。 您應該執行以下操作:
使用以下命令檢查該對象是否為JSONObject
:
JSONObject category=jsonObject.optJSONObject("Category");
如果category
對象不是json對象,它將返回JSONObject
或null
。 然后執行以下操作:
JSONArray categories;
if(category == null)
categories=jsonObject.optJSONArray("Category");
如果它不是有效的JSONArray
,它將返回您的JSONArray
或null。
即使你有答案,但它仍然可以幫助其他用戶......
if (Law.get("LawSet") instanceof JSONObject)
{
JSONObject Lawset = Law.getJSONObject("LawSet");
}
else if (Law.get("LawSet") instanceof JSONArray)
{
JSONArray Lawset = Law.getJSONArray("LawSet");
}
這里的Law
是其他JSONObject
, LawSet
是你想要找到的JSONObject or JSONArray
。
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()
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());
}
}
您可以使用instanceof
來檢查所獲得的結果的類型。 然后你可以隨意處理它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.