asiya asiya - 5 months ago 6
JSON Question

how to parse this jsonarray using GSON library

This is my jsonarray.

[
{
"id": 3,
"title": "Best Seller",
"promotedProducts": [
{
"product": {
"id": 4208,
"name": "Gents T-Shirt With Navy Blue Collar cuff",
"reviewList": [],
"productDetail": {
"id": 4207,
"length": 33,
"breadth": 27
},
"attributeList": [
{
"id": 1,
"productId": 4208
}
]
}
},
{
"product": {
"id": 4208,
"name": "Gents T-Shirt With Navy Blue Collar cuff",
"reviewList": [],
"productDetail": {
"id": 4207,
"length": 33,
"breadth": 27
},
"attributeList": [
{
"id": 1,
"productId": 4208
}
]
}
}
]
}
]


I had created Homecollection class for it.also added following code for parsing.I had also created subclasses for product,promotedProducts,productDetail,attributeList,images.its give me as reponse of two items but other details are coming empty

Gson gson = new Gson();
HomeProducts homeProducts = HomeProducts.getInstance();
List<HomeCollections> collectionList = new ArrayList<HomeCollections>();
collectionList = Arrays.asList(gson.fromJson(response.toString(), HomeCollections[].class));

Answer

Create a Model class like this.

public class ProductDetail
    {
        public int id { get; set; }
        public int length { get; set; }
        public int breadth { get; set; }
    }

public class AttributeList
{
    public int id { get; set; }
    public int productId { get; set; }
}

public class Product
{
    public int id { get; set; }
    public string name { get; set; }
    public List<object> reviewList { get; set; }
    public ProductDetail productDetail { get; set; }
    public List<AttributeList> attributeList { get; set; }
}

public class PromotedProduct
{
    public Product product { get; set; }
}

public class HomeCollections
{
    public int id { get; set; }
    public string title { get; set; }
    public List<PromotedProduct> promotedProducts { get; set; }
}

Now use the GSON like this. Here url is the source link.You will get the response as a model. Now

response.promotedProducts will give you all list of items.

    InputStream source = retrieveStream(url);
    Gson gson = new Gson();
    Reader reader = new InputStreamReader(source);
    HomeCollections response = gson.fromJson(reader, HomeCollections.class);
Comments