Reputation: 33
I'm very new to Java and trying to find and check whether a particular value exists in JSON object. Here is my code,
String strUsers = representation.getText();
JSONObject jsonObject = new JSONObject(strUsers);
Iterator<String> keys = jsonObj.keys();
while(keys.hasNext()) {
String key = keys.next();
String val = null;
try {
JSONObject value = jsonObj.getJSONObject(key);
} catch(Exception e) {
}
}
Further I'm not able to understand how to check. Can any one guide me in achieving my goal?
Upvotes: 1
Views: 4274
Reputation: 4733
You should use the method has
.
if(jsonObject.has("your_key")) {
// get the value and do something with it
}
In your try-catch
block, before getting the value check if the key actually exists.
if (jsonObject.has(key)) {
// then get the value
JSONObject value = jsonObj.getJSONObject(key);
}
Upvotes: 5