我知道这个问题经常被提出来,但到目前为止我还没找到答案......
我正在尝试将Android与GSON配合使用。我想使用JSON字符串来填充Gridview,但我不知道如何访问嵌套对象。
JSON文件:
[{'ProductCategories':[
{
'name':'Cat1', 'Product Series':[
{
'name':'ProdSeries1', 'Description':'Lorem Ipsum Bla Bla','Products':[
{
'name':'Product1','key':'value','key':'...'
},
{
'name':'Product2','key':'value','key':'...'
},
]
}
]
},
]
}]
我制作了4个课程:Products
,ProductSeries
,ProductCatalog
和ProductCategory
。
示例:
public class ProductCatalog {
@SerializedName("ProductCategories")
@Expose
private List<ProductCategory> productCategories = null;
public List<ProductCategory> getProductCategories() {
return productCategories;
}
public void setProductCategories(List<ProductCategory> productCategories) {
this.productCategories = productCategories;
}
}
之后我用gson解析了JSON:
Gson gson = new Gson();
Type type = new TypeToken<List<ProductCatalog>>(){}.getType();
List<ProductCatalog> productcatalog = gson.fromJson(JSONstring,type);
现在我有一个已解析的JSON数据列表,但不知道如何使用嵌套对象,例如&#39; Product1&#39;。我认为吸气剂会有所帮助,但我无法在我的活动中访问getProductCategories()
。我怎么能这样做?
答案 0 :(得分:0)
如果您使用Gson意味着这将有助于您
public class MainClazz {
@SerializedName("ProductCategories")
@Expose
private List<ProductCategory> productCategories = null;
public List<ProductCategory> getProductCategories() {
return productCategories;
}
public void setProductCategories(List<ProductCategory> productCategories) {
this.productCategories = productCategories;
}
}
public class Product {
@SerializedName("name")
@Expose
private String name;
@SerializedName("key")
@Expose
private String key;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
public class ProductCategory {
@SerializedName("name")
@Expose
private String name;
@SerializedName("Product Series")
@Expose
private List<ProductSeries> productSeries = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ProductSeries> getProductSeries() {
return productSeries;
}
public void setProductSeries(List<ProductSeries> productSeries) {
this.productSeries = productSeries;
}
}
public class ProductSeries {
@SerializedName("name")
@Expose
private String name;
@SerializedName("Description")
@Expose
private String description;
@SerializedName("Products")
@Expose
private List<Product> products = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}