【问题标题】:Fetch value from JSON array based on another value in the array根据数组中的另一个值从 JSON 数组中获取值
【发布时间】:2017-08-10 19:48:59
【问题描述】:

这是我的 JSON 响应:

[  
   {  
      "name":"Canara Atm",
      "location_name":"Baker Junction"
   },
   {  
      "name":"Canara Atm",
      "location_name":"Manarcaud"
   },
   {  
      "name":"Canara Atm",
      "location_name":"Palai Arunapuram"
   },
   {  
      "name":"Canara Atm",
      "location_name":"Changanacherry"
   }
]

我需要根据特定位置添加值到数组中,例如 location_name":"Baker Junction" 是我需要的位置,然后我应该只添加指定的 atm 名称到我的数组中。下面的代码所有名称都被添加到数组中

   try {
       JSONArray jsonArray = new JSONArray(response);
       JSONObject json = null;
       final String xcoords[] = new String[jsonArray.length()];
       if (jsonArray.length() != 0) {
           for (int i = 0; i < jsonArray.length(); i++) {
               json = jsonArray.getJSONObject(i);
               xcoords[i] = (json.getString("name"));

           }
       }
   }

【问题讨论】:

  • 我不太明白。您希望将特定单个(!)“location_name”(例如:Baker Junction)的“名称”添加到固定长度的字符串数组中。那不只是一个只有一个值的 X 长度数组吗?所以你的数组中的 X-1 个条目是空的?
  • 问题的状态是什么?如果给出的答案解决了它,请考虑接受答案,以便将您的问题标记为已解决并正确执行。这有助于让每个人都知道不需要更多的答案。对于已解决的任何其他问题,您应该这样做。

标签: java android json android-volley


【解决方案1】:

这就是我所做的,您可以将 json 转换为如下所示的列表,

ArrayList<String> list = new ArrayList<>();
 for (int i = 0; i < jsonArray.length(); i++) {
               json = jsonArray.getJSONObject(i);
              Strring s = (json.getString("name"));
               list.add(p)
           }

然后

//you can directly use this value or you can use the index to again fetch the json or for other purpose
        int count =0;
        int index = 0 ;
        for(Sting s : list){
        if(s.equals("yourvalue"){
             index = count;
           }
          count++
         }

然后

if (jsonArray.length() != 0) {
           for (int i = 0; i < jsonArray.length(); i++) {
             // your index here
               json = jsonArray.getJSONObject(index);
               xcoords[i] = (json.getString("name"));

           }
       }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    相关资源
    最近更新 更多