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

Upvotes: 4

Views: 28084

Answers (3)

LGenzelis
LGenzelis

Reputation: 824

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.

Upvotes: 1

kraskevich
kraskevich

Reputation: 18546

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 http://www.json.org/javadoc/org/json/JSONArray.html.

Upvotes: 10

wassgren
wassgren

Reputation: 19201

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))

Upvotes: 2

Related Questions