Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Json has key/field

Tags:

java

json

I'd like to know the most simple way to detect if a key/field exists in a JSON String.

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.

Answer: JSONObject jsonObj2 = new JSONObject(message); if(jsonObj2.has("key"));

like image 730
basickarl Avatar asked Nov 04 '13 19:11

basickarl


People also ask

How do I check if a json object has a key?

has() method – Class JsonObject. This is the convenience method that can be used to check of a property/member with the specified key is present in the JsonObject or not. This method returns true if the member with specified key exists, otherwise it returns false.

How do you check if a key exists in a JSON string in Java?

Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().

Does JSON need a key?

JSON keys are on the left side of the colon. They need to be wrapped in double quotation marks, as in "key" , and can be any valid string. Within each object, keys need to be unique.

Can an object be a key in JSON?

JSON objects are written in key/value pairs. JSON objects are surrounded by curly braces { } . Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Keys and values are separated by a colon.


2 Answers

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.

like image 72
Bizmarck Avatar answered Oct 11 '22 18:10

Bizmarck


In minimal-json, you'd write:

if (JsonObject.readFrom(myJsonString).get("myKey") != null) {
  ...
}
like image 2
ralfstx Avatar answered Oct 11 '22 18:10

ralfstx