Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search element in a JSONArray in Java

Tags:

java

arrays

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

like image 392
Giancarlo Ventura Granados Avatar asked Dec 12 '22 01:12

Giancarlo Ventura Granados


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

like image 174
kraskevich Avatar answered Dec 20 '22 01:12

kraskevich


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))
like image 24
wassgren Avatar answered Dec 20 '22 03:12

wassgren