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
43 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 .
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)) 1You 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.