开发者

Porting from one Json to javas org.json.JSONObject, missing keys not acting the same

I have code in a method that I ported that now throws JSONException in my newly created java code.

Below does not work as it used to:

    if (theEvent.getString("plugin")== null)
    {
        processNonPluginEvent(theEvent);
        return;
    }

I found out using

org.json.JSONObject 

behaves differently than it did on my old code using a different JSON library in c#. The above code always gets caught by an exception. In my old code if a key didn't exist it would return null. Do I really have to catch for that exception in the event the key doesn't exsist? or is there another way I have not yet discovered to tell if my org.json.JSONObject has a key or not in it?

for reference the old c# code looked like:

  if (theEvent["plugin"] == null)
  {
       processNonPluginEvent(theEvent);
       return;开发者_如何学JAVA
  }


Assuming you are using the code from this library, I believe you want:

if (!theEvent.has("plugin"))
{
    processNonPluginEvent(theEvent);
    return;
}

Check out the documentation for the JSONObject class:

http://www.json.org/javadoc/org/json/JSONObject.html

Also, all classes from the library are documented here.


To see if the JSONObject has a key, use the JSONObject.has(String key) function.

e.g.

if (!theEvent.has("plugin")) {
    processNonPluginEvent(theEvent);
}

From the JavaDoc, the has() function:

Determine if the JSONObject contains a specific key.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜