2017-07-11 119 views
1

我想知道遍历此ArrayList的最佳方法,此ArrayList来自来自API的响应,这是该ArrayList: enter image description here迭代ArrayList的

的问题是,我不知道如何让“ ID”和‘价值’从环, 我知道ArrayList的大小,但我没有任何想法如何打印‘从这个阵列

 for(int i=1; i <= contacts.size(); i++) { 
     //Example System.out.print(contacts[i]->id); 
     //Example System.out.print(contacts[i]->contact_name) ; 
     //Example System.out.print(contacts[i]->numbers); 
     //Example System.out.print(contacts[i]->emails); 
     //I want to print id and value 
     // 
    } 

在onResponse我把这种温控功能键’和‘值’例如:

ServerResponse resp = response.body(); 
functionExample((ArrayList) resp.getResponse()); 

functionExample有一个ArrayList作为参数。 这是从我的resp.getResponse我的结果():

enter image description here

这是我的JSON从API:

{ 
"result": "success", 
"message": "Lista de Contactos", 
"response": [ 
    { 
     "id": 1, 
     "contact_name": "EDIFICADORA JUANA", 
     "numbers": "{24602254,55655545}", 
     "emails": "{[email protected],[email protected]}" 
    }, 
    { 
     "id": 2, 
     "contact_name": "LA MEJOR", 
     "numbers": "{25445877,25845877}", 
     "emails": "{[email protected]}" 
    } 
    ] 
} 

我感谢所有帮助。

+0

哪里是你的JSON? – AbhayBohra

+0

研究使用'JSONObject'和'JSONArray'。这些是您将用于Android的最基本的工具。 –

回答

1
public void FunctionExample(ArrayList contacts) { 

    for(int i=0; i < contacts.size(); i++) { 

     LinkedTreeMap<String, Object> map = (LinkedTreeMap<String, Object>) contacts.get(i); 
     map.containsKey("id"); 
     String id = (String) map.get("id"); 
     map.containsKey("contact_name"); 
     String contact_name = (String) map.get("contact_name"); 
     map.containsKey("numbers"); 
     String numbers = (String) map.get("numbers"); 
     numbers.replace("{","").replace("}",""); 
     map.containsKey("emails"); 
     String emails = (String) map.get("emails"); 
     emails.replace("{","").replace("}",""); 

     Snackbar.make(getView(), id, Snackbar.LENGTH_LONG).show(); 
     Snackbar.make(getView(), contact_name, Snackbar.LENGTH_LONG).show(); 
     Snackbar.make(getView(), numbers, Snackbar.LENGTH_LONG).show(); 
     Snackbar.make(getView(), emails, Snackbar.LENGTH_LONG).show(); 

    } 
} 
1

尝试,如果你正在使用ArrayList<TreeMap<String, String>> contacts this..It会给ID的

JSONObject object=new JSONObject(response); 
    JSONArray array= null; 
    try { 
     array = object.getJSONArray("response"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    ArrayList<String> idArray=new ArrayList<>(); 
    for(int i=0;i< array.length();i++) 
    { 
     idArray.add(getJSONObject(i).getString("id")); 
    } 
1

尝试这样的ArrayList;

for(TreeMap<String,String> contact : contacts){ 
String id = contact.getValue("id"); 
} 
+0

我使用ServerResponse和此ServerResponse我解析到ArraList –

+0

什么是你的arrayList的结构? –

1

我强烈建议您使用例如杰克逊将您的JSON响应映射到适当的对象。考虑下面的例子:

import com.fasterxml.jackson.annotation.JsonProperty; 
import com.fasterxml.jackson.databind.ObjectMapper; 

import org.junit.Test; 

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 
import java.util.stream.Collectors; 
import java.util.stream.Stream; 

public class JacksonTest { 

    private static final String JSON = "{\n" + 
      "\"result\": \"success\",\n" + 
      "\"message\": \"Lista de Contactos\",\n" + 
      "\"response\": [\n" + 
      " {\n" + 
      "  \"id\": 1,\n" + 
      "  \"contact_name\": \"EDIFICADORA JUANA\",\n" + 
      "  \"numbers\": \"{24602254,55655545}\",\n" + 
      "  \"emails\": \"{[email protected],[email protected]}\"\n" + 
      " },\n" + 
      " {\n" + 
      "  \"id\": 2,\n" + 
      "  \"contact_name\": \"LA MEJOR\",\n" + 
      "  \"numbers\": \"{25445877,25845877}\",\n" + 
      "  \"emails\": \"{[email protected]}\"\n" + 
      " }\n" + 
      " ]\n" + 
      "}"; 

    @Test 
    public void testParsingJSONStringWithObjectMapper() throws IOException { 
     //given: 
     final ObjectMapper objectMapper = new ObjectMapper(); 

     //when: 
     final Response response = objectMapper.readValue(JSON, Response.class); 

     //then: 
     assert response.getMessage().equals("Lista de Contactos"); 
     //and: 
     assert response.getResult().equals("success"); 
     //and: 
     assert response.getResponse().get(0).getId().equals(1); 
     //and: 
     assert response.getResponse().get(0).getContactName().equals("EDIFICADORA JUANA"); 
     //and: 
     assert response.getResponse().get(0).getEmails().equals(Arrays.asList("[email protected]", "[email protected]")); 
     //and: 
     assert response.getResponse().get(0).getNumbers().equals(Arrays.asList(24602254, 55655545)); 
    } 

    static class Response { 
     private String result; 
     private String message; 
     private List<Data> response = new ArrayList<>(); 

     public String getResult() { 
      return result; 
     } 

     public void setResult(String result) { 
      this.result = result; 
     } 

     public String getMessage() { 
      return message; 
     } 

     public void setMessage(String message) { 
      this.message = message; 
     } 

     public List<Data> getResponse() { 
      return response; 
     } 

     public void setResponse(List<Data> response) { 
      this.response = response; 
     } 
    } 

    static class Data { 
     private String id; 
     @JsonProperty("contact_name") 
     private String contactName; 
     private String numbers; 
     private String emails; 

     public String getId() { 
      return id; 
     } 

     public void setId(String id) { 
      this.id = id; 
     } 

     public String getContactName() { 
      return contactName; 
     } 

     public void setContactName(String contactName) { 
      this.contactName = contactName; 
     } 

     public List<Integer> getNumbers() { 
      return Stream.of(numbers.replaceAll("\\{", "") 
        .replaceAll("}", "") 
        .split(",")) 
        .map(Integer::valueOf) 
        .collect(Collectors.toList()); 
     } 

     public void setNumbers(String numbers) { 
      this.numbers = numbers; 
     } 

     public List<String> getEmails() { 
      return Arrays.asList(emails.replaceAll("\\{", "") 
        .replaceAll("}", "") 
        .split(",")); 
     } 

     public void setEmails(String emails) { 
      this.emails = emails; 
     } 
    } 
} 

在这个例子中我用相同JSON响应收到和jackson-core库(http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.8.9)用于映射字符串到的POJO(而不是字符串可以使用的InputStream,字节[]等)。有两个POJO:ResponseData。响应汇总了一个Data对象的列表。此外,DatagetEmails()getNumbers()方法将您的输入字符串解析为期望对象的列表。例如,如果您致电setNumbers("{24602254,55655545}"),则getNumbers()将返回一个整数列表(您可以使用任何数字类型),如[24602254, 55655545]

其他建议也是有效的,例如,迭代收集TreeMap s或JSONObject s。在这个例子中,我们将重点放在处理具有特定类型的Java对象上,而不是处理基本类如Object类。

最终的解决方案还取决于您的运行时环境。在这种情况下,您将不得不添加jackson-core依赖关系 - 如果您的项目因其他原因已经使用Jackson,则更有意义。

0

试试这个循环从ArrayList中提取你的

List<LinkedTreeMap> list = new ArrayList<LinkedTreeMap>(); //assign result from API to list 
    for(LinkedTreeMap<String,String> contact : list){ 
     for(String id : contact.keySet()){ 
      if(id.equalsIgnoreCase("id")){ 
       System.out.println("ID: "+ contact.get(id)); 
      }else if(id.equalsIgnoreCase("contact_name")){ 
       System.out.println("Contact Name: "+ contact.get(id)); 
      }else{ //if it is list of numbers or e-mails 
       String result = contact.get(id); 
       result = result.replaceAll("{|}", ""); //removing { } 
       String[] array = result.split(","); 
       System.out.println(id+": "); // this will be either numbers or e-mails 
       //now iterating to get each value 
       for(String s : array){ 
        System.out.println(s); 
       } 
      } 
     } 
    } 
1

的每一个值如果你正在使用设置<地图<字符串,字符串>>设置;

set.stream().forEach(map -> { 
     System.out.print("Id:" + map.get("id") + "ContactName:" + map.get("contact_name")); 
    }); 
+0

我使用ServerResponse和这个ServerResponse我解析到ArraList –

+0

@JohanSánchez你仍然可以使用ArrayList的流。不要设置,给你的数组引用。 –