1

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?

1 Answer 1

5

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Alessandro. Can you give me a very basic example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.