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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:06:10  来源:igfitidea点击:

Java: Json has key/field

javajson

提问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.jsonpackage simple and straightforward (i.e. minimal overhead). It is found here. The org.json.JSONObjectclass, 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) {
  ...
}