How to parse Json Array using gson in android

I am developing an Android application and I am using gson to parse the json response. My json answer looks like

[{"customerid":"abc","customername":"abc","location":null} ,{"customerid":"xyz","customername":"xyz","location":null}] 

And the class to parse this answer is as follows:

 public class CustomerInfo { @SerializedName("customerid") public String customerid; @SerializedName("customername") public String customername; @SerializedName("location") public String location; public CustomerInfo() {} } 

I tried this as follows:

  Gson gson = new Gson(); List<CustomerInfo> customers = (List<CustomerInfo>)gson.fromJson(result,CustomerInfo.class); 

But it does not work for me. How to do it. Need help. Thanks.

+4
source share
1 answer

First you create getters and setters for all your variables inside the CustomerInfo class ie for customerid, customername and location, then you can parse JSON using the code snippet below:

 Gson gson = new Gson(); JsonData gsonData = gson.fromJson(response, CustomerInfo.class); for (int j = 0; j < gsonData.getCount(); j++) { String customerid = gsonData.get(j).getCustomerId(); String customername = gsonData.get(j).getCustomerName(); String location = gsonData.get(j).getLocation(); } 
+2
source

Source: https://habr.com/ru/post/1498574/


All Articles