[英]Parse json field that may be an JSONObject or JSONArray in java
我正在使用json.org庫來解析我的json。 但是我有一個稱為“消息”的字段,根據消息的數量可能為空字段,如果有多個消息,則為JSONObject(如果只有一條消息),或者為JSONArray。 我在處理此問題時遇到了麻煩,因為我必須使用正確的對象類型來讀取它,因為如果我做對的話它將返回錯誤。 哦,是java。
誰能幫我? 我敢肯定有一種“標准”的方式來解決這個問題!
我只是創建一個簡單的實用程序方法,如下所示:
private void processMessages(Object messages) {
JSONArray jsonArr;
if (messages instanceof JSONObject) {
jsonArr = new JSONArray();
jsonArr.put(messages);
} else if (messages instanceof JSONArray) {
jsonArr = messages;
}
// Process all the JSONObjects in the same way
for (final JSONObject obj : jsonArr) {
}
}
然后從您的代碼中:
if (jsonObj.has("messages")) {
processMessages(jsonObj.get("messages"));
}
假設您正在使用JSONTokener :
JSONTokener jk = ...; // whatever you're currently doing.
// Probably a loop here around the below...
Object o = jk.nextValue();
if(o instanceof JSONObject){
JSONObject jo = (JSONObject)o;
// Do something with jo.
}else if(o instanceof JSONArray){
JSONArray ja = (JSONArray)o;
// Do something with ja.
}else{
// Is null or another type. (Maybe do something?)
}
有關nextValue()
返回的所有其他類型,請參見http://www.json.org/javadoc/org/json/JSONTokener.html#nextValue%28%29 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.