Search Element in a Jsonarray in Java

I have a JSONArray in Java like this: ["1","2","45","354"] Then, I want to search for an element into this array. For example, to check if "44" is into the array. I try

boolean flag = false;
for (int i = 0; i < jsonArray.length(); i++) {
  if (jsonArray[i]= myElementToSearch){
    flag = true;
  }
}

But I cant get an error, because It has results in an Array, not in a JSONArray

How can I comprobe if an element is present in a JSONArray?

myElementToSearch is a String

4

3 Answers

It should look like this:

boolean found = false;
for (int i = 0; i < jsonArray.length(); i++)
    if (jsonArray.getString(i).equals(myElementToSearch))
        found = true;

I assume that jsonArray has type .

0

If the object you are comparing against is a primitive type (e.g. int) then try comparing instead of assigning the value.

// Comparing
if (jsonArray[i] == myElementToSearch)

vs

// Assigning
if (jsonArray[i] = myElementToSearch)

If it is an object, such as a String the equals-method should be used for comparing:

// Comparing objects (not primitives)
if (myElementToSearch.equals(jsonArray[i]))

And, if the array is a org.json.JSONArray you use the following for accessing the values:

myElementToSearch.equals(jsonArray.getString(i))
1

You could try something like this:

boolean flag = false;
for (int i = 0; i < jsonArray.length(); i++) {
  if (jsonArray.get(i).toString().equals(myElementToSearch)){
    flag = true;
    break;
  }
}

Note that I added "break", so that, if your element is found, it doesn't keep looking for it.

Your Answer

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

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest