Java:Json 有键/字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19775291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Json has key/field
提问by Karl Morrison
I'd like to know the most simple way to detect if a key/field exists in a JSON String.
我想知道检测 JSON 字符串中是否存在键/字段的最简单方法。
for example:
例如:
if(jsonObject(myJsonString).hasKey("myKey")){
}
I would not prefer to write a lot. I am currently using minimal JSON and it appears it does not have such a function.
我不想写很多。我目前使用的是最小的 JSON,它似乎没有这样的功能。
Answer: JSONObject jsonObj2 = new JSONObject(message); if(jsonObj2.has("key"));
答案:JSONObject jsonObj2 = new JSONObject(message); if(jsonObj2.has("key"));
采纳答案by Bizmarck
Not sure what you mean exactly by minimal JSON, personally I find the org.json
package simple and straightforward (i.e. minimal overhead). It is found here. The org.json.JSONObject
class, for example, contains the public boolean has(String key)
method, which is used to check if a certain key exists.
不确定最小 JSON 的确切含义,我个人认为该org.json
包简单明了(即最小开销)。可以在这里找到。的org.json.JSONObject
类,例如,包含了public boolean has(String key)
方法,其用于检查是否有某个键存在。
回答by ralfstx
In minimal-json, you'd write:
在minimum-json,你会写:
if (JsonObject.readFrom(myJsonString).get("myKey") != null) {
...
}