传递JSON数组 - Android

时间:2015-12-13 09:36:18

标签: java android json

我正在编写一个简单的Web服务,使用php和mysql作为服务器,使用android app作为客户端来检索数据。

我进行查询时,我的服务器端返回此JSON数组。

"customers":[
    {"firstName":"Jason", "lastName":"Smith"},
    {"firstName":"Joan", "lastName":"Smith"},
    {"firstName":"Jennifer", "lastName":"Jones"}
]

我的问题是如何将这个JSON数组解析成ArrayList以便稍后使用。

先谢谢你。

5 个答案:

答案 0 :(得分:1)

你可以这样做:

String jsonStr; // your JSON string
JSONArray jsonArray = new JSONArray(jsonStr);

for(int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObj = jsonArray.getJSONObject(i);
    String firstname = jsonObj.getString("firstname");
    String lastname = jsonObj.getString("lastname");
}

答案 1 :(得分:1)

myData

类型的数组列表
 List<myData> listData = new ArrayList<myData>(); 
 JSONArray jsonArray = new JSONArray("your response json string");

                for(int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObj = jsonArray.getJSONObject(i);
                    listData.add(new myData(jsonObj.getString("firstname"),jsonObj.getString("lastname")));
                }
// your ArrayList is ready, and you can use it anytime.

您的名字和姓氏的数据结构

<强> myData.java

public class myData {
String firstName, lastName;
myData(String fName, String lName) {
    this.firstName = fName;
    this.lastName = lName;
}
}

答案 2 :(得分:0)

使用GSON

        public class Customer{
            String firstName;
            String lastName;

            public static class List extends ArrayList<Customer>{

            }
        }
        public static Customer.List getCustomersList(String jsonString){
            Gson gson = new GsonBuilder().create();
            return gson.fromJson(jsonString, Customer.List.class);
        }

答案 3 :(得分:-1)

使用GSONJackson等库。

答案 4 :(得分:-1)

如果没有GSONJackson

,您可以这样做
ArrayList<HashMap<String, String>>  listCustomer= new ArrayList<HashMap<String,String>>();
    JSONArray jsonArray = new JSONArray(jsonStr);

    for(int i = 0; i < jsonArray.length(); i++) {
        HashMap<String, String> mapCustomer = new HashMap<String, String>();
        JSONObject jsonObj = jsonArray.getJSONObject(i);

        mapCustomer.put("firstname", jsonObj.getString(firstname));
        mapCustomer.put("lastname", jsonObj.getString(lastname));

        listCustomer.add(mapCustomer);

    }