1

I need to get "examples" data that is an array inside of 'results'

JSON FILE

and append it to a string. What would be the easiest way to do that?

this is how i would get "definitions"

private JSONObject queryResults;
...
...
    String finalResults = "";
    JSONArray results = queryResults.getJSONArray("results");
    for(int i = 0; i < results.length(); i++){
        JSONObject item = results.getJSONObject(i);
        finalResults += item.getString("definition") + " ";
    }

1 Answer 1

2

As this topic is related to Android application, the easiest way to get the mentioned value without using any additional libraries is to check if JSONObject inside the for-loop has attribute definitions and get the value as a String. You can go with it like this

String finalExamples = "";
JSONArray results = queryResults.getJSONArray("results");
for (int i=0; i < results.length(), i++) {
    JSONObject item = results.getJSONObject(i);
    if (item.has("examples")) {
        examples += item.getString("examples");
    }   
}

I assumed that you don't want to update your result String value if examples is not available in the JSONObject. If you want to handle other cases, for example when "examples" is available in the object but is null or is set to empty String you can use other methods of JSONObject to check it. More info about working with JSONObjects you can find in the documentation

Sign up to request clarification or add additional context in comments.

2 Comments

That is exactly the solution i expected, thank you very much! I tried to approach the problem similarly, but did not knew about .has method. And in my case, there is no need to check for null objects
It's always a good idea to check the SDK/library docs when you are not sure which method is one that you need. Also I guess that you are working with the Android Studio which is based on IntelliJ IDEA, so after typing variable name with a dot it should display a list of available methods. This also can help.

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.