更好的方法来确定是否值JSON提要存在方法来、提要、存在、JSON

2023-09-05 07:36:21 作者:年轻在于拼

我使用的Andr​​oid应用程序的 org.json.JSONObject (和语法分析器)来分析一个JSON提要。这是确定一个属性存在与否的对象之一的最佳途径回来了?

I'm using the org.json.JSONObject (and parser) in an Android app to parse a JSON feed. Which is the best way to determine if a property exists or not in one of the objects returned?

说我有一个JSON提要包括新闻。一些消息也被称为房地产UnpublishDate(这是新闻的问题不再生效的日期),而一些消息没有这个属性。

Say I have a JSON feed including "News". Some of the news have a property called "UnpublishDate" (which is the date the news in question is no longer active), while some of the news don't have this property.

我已经出来(虽然尚未实现)最好的解决办法是简单地拥有的try-catch围绕 theJSONObject.get(UnpublishDate) - 你知道的任何更好的解决方案(即更加婀娜多姿当类扩展到JSON的饲料中几个选属性)

The best solution I've come up with (though not implemented yet) is to simply have a "try-catch" around the theJSONObject.get("UnpublishDate") - do you know of any better solution (that is more graceful when the class scales to several "optional" properties in the JSON feed)?

推荐答案

您可以使用的JSONObject 函数

if(myJSONObject.has("UnpublishDate")) {
    //it has it, do appropriate processing
}