4

I am developing android application and I am using gson for parsing json response. My json responce looks like

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

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

And class for parsing this response looks like :

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

    @SerializedName("customername")
    public String customername;

    @SerializedName("location")
    public String location;

    public CustomerInfo()
    {}
}

I tried it in following way:

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

But its not working for me. How to do this. Need Help. Thank you.

nilkash
  • 7,408
  • 32
  • 99
  • 176

1 Answers1

3

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

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();
}
Navjot
  • 1,202
  • 1
  • 11
  • 24
  • 1
    JsonData gsonData = gson.fromJson ??!!! – Jithu Jan 31 '14 at 06:51
  • JsonData gsonData = gson.fromJson(response, CustomerInfo.class); // response is in string and CustomerInfo.class is the class to which json is parsed – Navjot Feb 01 '14 at 15:55