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
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With