繁体   English   中英

解析可能是Java中的JSONObject或JSONArray的json字段

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM