0

I'm writing an simple web service, using php and mysql as server and android app as client to retrieve data.

My server side returns this JSON array when I make a query.

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

My question is how to parse this JSON array into ArrayList for using later.

Thank you in advanced.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
Lucky Luke
  • 609
  • 1
  • 6
  • 18
  • Possible duplicate of [Sending and Parsing JSON Objects](http://stackoverflow.com/questions/2818697/sending-and-parsing-json-objects) – Tim Malseed Dec 13 '15 at 09:37

5 Answers5

1

You can proceed this way:

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");
}
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
1

Your array list of type 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.

Your data structure for firstname and lastname

myData.java

public class myData {
String firstName, lastName;
myData(String fName, String lName) {
    this.firstName = fName;
    this.lastName = lName;
}
}
Aman Gupta - ΔMΔN
  • 2,971
  • 2
  • 19
  • 39
0

Use 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);
        }
Nick
  • 949
  • 1
  • 11
  • 31
-1

Use libraries like GSON or Jackson.

Vamsi
  • 878
  • 1
  • 8
  • 25
-1

You can do like this without GSON or Jackson

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

    }
Kishore Jethava
  • 6,666
  • 5
  • 35
  • 51