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"));
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.
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().
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.
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.
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.
In minimal-json, you'd write:
if (JsonObject.readFrom(myJsonString).get("myKey") != null) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With