Java 通过键 jsonarray 获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42549545/
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
get value by key jsonarray
提问by mmu36478
JSONArray arr =
[
{"key1":"value1"},
{"key2":"value2"},
{"key3":"value3"},
{"key4":"value4"}
]
arr.get("key1")
throws error. How can I get the value by key in JSONArray
?
arr.get("key1")
抛出错误。如何通过键入获取值JSONArray
?
arr.getString("key1")
also throws error. Should I loop through the array? Is it the only way to do it?
arr.getString("key1")
也会抛出错误。我应该遍历数组吗?这是唯一的方法吗?
What is the error?
错误是什么?
In Eclipse Debug perspective, these expressions returns as; error(s)_during_the_evaluation
在 Eclipse Debug 透视图中,这些表达式返回为; error(s)_during_the_evaluation
采纳答案by Chetan Joshi
You can parse your jsonResponse
like below code :
您可以解析jsonResponse
以下代码:
private void parseJsonData(String jsonResponse){
try
{
JSONArray jsonArray = new JSONArray(jsonResponse);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String value1 = jsonObject1.optString("key1");
String value2 = jsonObject1.optString("key2");
String value3 = jsonObject1.optString("key3");
String value4 = jsonObject1.optString("key4");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
回答by Ravi MCA
for (int i = 0; i < arr.length(); ++i) {
JSONObject jsn = arr.getJSONObject(i);
String keyVal = jsn.getString("key1");
}
You need to iterate through the array to get each JSONObject. Once you have the object of json you can get values
by using keys
您需要遍历数组以获取每个 JSONObject。一旦你有了 json 的对象,你就可以values
使用keys
回答by dwhite5914
Sounds like you want to find a specific key from an array of JSONObjects. Problem is, it's an array, so you have to iterate over each element. One solution, assuming no repeat keys is...
听起来您想从 JSONObjects 数组中查找特定键。问题是,它是一个数组,所以你必须遍历每个元素。一种解决方案,假设没有重复键是......
private Object getKey(JSONArray array, String key)
{
Object value = null;
for (int i = 0; i < array.length(); i++)
{
JSONObject item = array.getJSONObject(i);
if (item.keySet().contains(key))
{
value = item.get(key);
break;
}
}
return value;
}
Now, let's say you want to find the value of "key1" in the array. You can get the value using the line: String value = (String) getKey(array, "key1")
. We cast to a string because we know "key1" refers to a string object.
现在,假设您想在数组中找到“key1”的值。您可以使用以下行获取值:String value = (String) getKey(array, "key1")
。我们转换为字符串是因为我们知道“key1”指的是一个字符串对象。
回答by Jhollman
You can easy get a JSON array element by key like this:
您可以通过这样的键轻松获取 JSON 数组元素:
var value = ArrName['key_1']; //<- ArrName is the name of your array
console.log(value);
Alternatively you can do this too:
或者,您也可以这样做:
var value = ArrName.key_1;
That's it!
就是这样!