简体   繁体   English

通过密钥jsonarray获取价值

[英]get value by key jsonarray

JSONArray arr = 
[
    {"key1":"value1"},
    {"key2":"value2"},
    {"key3":"value3"},
    {"key4":"value4"}
]

arr.get("key1") throws error. arr.get("key1")抛出错误。 How can I get the value by key in JSONArray ? 如何通过JSONArray的键获取值?

arr.getString("key1") also throws error. arr.getString("key1")也会抛出错误。 Should I loop through the array? 我应该循环播放数组吗? Is it the only way to do it? 这是唯一的方法吗?

What is the error? 错误是什么?

In Eclipse Debug perspective, these expressions returns as; 在Eclipse Debug透视图中,这些表达式返回为; error(s)_during_the_evaluation

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();
        }
    }

Sounds like you want to find a specific key from an array of JSONObjects. 听起来你想从JSONObjects数组中找到一个特定的键。 Problem is, it's an array, so you have to iterate over each element. 问题是,它是一个数组,所以你必须迭代每个元素。 One solution, assuming no repeat keys is... 一个解决方案,假设没有重复键是......

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. 现在,假设您要在数组中找到“key1”的值。 You can get the value using the line: String value = (String) getKey(array, "key1") . 您可以使用以下行获取值: String value = (String) getKey(array, "key1") We cast to a string because we know "key1" refers to a string object. 我们转换为字符串因为我们知道“key1”指的是一个字符串对象。

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. 您需要遍历数组以获取每个JSONObject。 Once you have the object of json you can get values by using keys 获得json的对象后,您可以使用keys获取values

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! 而已!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM