T.Nice T.Nice - 24 days ago 9
JSON Question

Parsing Json data using Gson

I have a

JsonObject
with the following content:

{
id: "6705",
title: "Moto1",
address: {
location: [
{
meta_key: "map_lat",
meta_value: "1.4567"
},
{
meta_key: "map_lng",
meta_value: "2.345"
}
]
},
price: "25",
sale: "25",
number: "1",
image: "http://example.com"
}


I'm trying to extract address's info with
Gson
library
I have the following Class

public class MotoClass {

private List<MotoBean> Moto;

public List<MotoBean> getMoto() {
return Moto;
}

public void setMoto(List<MotoBean> Moto) {
this.Moto = Moto;
}

public static class MotoBean {
private String id;
private String title;
private AddressBean address;
private String price;
private String sale;
private String number;
private String image;

public String getId() {
return id;
}

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

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public AddressBean getAddress() {
return address;
}

public void setAddress(AddressBean address) {
this.address = address;
}

public String getPrice() {
return price;
}

public void setPrice(String price) {
this.price = price;
}

public String getSale() {
return sale;
}

public void setSale(String sale) {
this.sale = sale;
}

public String getNumber() {
return number;
}

public void setNumber(String number) {
this.number = number;
}

public String getImage() {
return image;
}

public void setImage(String image) {
this.image = image;
}

public static class AddressBean {


private List<LocationBean> location;

public List<LocationBean> getLocation() {
return location;
}

public void setLocation(List<LocationBean> location) {
this.location = location;
}

public static class LocationBean {
private String meta_key;
private String meta_value;

public String getMeta_key() {
return meta_key;
}

public void setMeta_key(String meta_key) {
this.meta_key = meta_key;
}

public String getMeta_value() {
return meta_value;
}

public void setMeta_value(String meta_value) {
this.meta_value = meta_value;
}
}
}
}
}


But when I try to access to info with

Gson gson = new GsonBuilder().create();
Type collectionType = new TypeToken<Collection<MotoClass.MotoBean.AddressBean>>(){}.getType();
Collection<MotoClass.MotoBean.AddressBean> enums = gson.fromJson(response,collectionType);
MotoClass.MotoBean.AddressBean[] result = enums.toArray(new MotoClass.MotoBean.AddressBean[enums.size()]);
Log.d(TASK, String.valueOf(motoClass.getLocation()));


log
gives me
parseMoto: null

Some advice ? Thanks in advance

Answer

I find the final solution. It works like a charm

                 Gson gson = new Gson();
            Moto moto = gson.fromJson(responseStr,Moto.class);
         for (int i = 0; i<moto.getMoto().size();i++){
     Log.d(TAG,"onSuccess:EqL["+i+"]"+moto.getMoto().get(i).getTitle());
          }
Comments