Java 中 JSONArray 中的搜索元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27804619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search element in a JSONArray in Java
提问by Giancarlo Ventura Granados
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
我在 Java 中有一个这样的 JSONArray: ["1","2","45","354"] 然后,我想在这个数组中搜索一个元素。例如,检查“44”是否在数组中。我试试
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
但我不能得到错误,因为它的结果是一个数组,而不是一个 JSONArray
How can I comprobe if an element is present in a JSONArray?
如果 JSONArray 中存在元素,我如何进行组合?
myElementToSearch is a String
myElementToSearch 是一个字符串
回答by kraskevich
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.
我假设jsonArray
类型为http://www.json.org/javadoc/org/json/JSONArray.html。
回答by wassgren
If the object you are comparing against is a primitive type (e.g. int
) then try comparinginstead of assigning the value.
如果您要比较的对象是原始类型(例如int
),则尝试比较而不是分配值。
// 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:
如果它是一个对象,如String
在equals
-method应该用于比较:
// 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:
并且,如果数组是 aorg.json.JSONArray
您使用以下来访问值:
myElementToSearch.equals(jsonArray.getString(i))
回答by LGenzelis
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.
请注意,我添加了“break”,因此,如果找到了您的元素,它就不会继续寻找它。