问问题
385 次
2 回答
0
可以解析同一级别的对象的不同命名。在一种方式中,可以定义@SerializedName(value="name1", alternate={"name2", "name3"}) String b;
含义,定义对象的替代名称。但要小心这个对象需要有相同的数据。在您的情况下,它将在所有情况下解析"id","name",因为 json 在所有情况下都包含这两个字段。
另一方面,当您想要解析所有字段时,最好使用自定义JsonDeserializer。您可以在此处找到如何为 GSON 库编写自己的反序列化器的示例:反序列化器
于 2018-12-11T19:31:06.320 回答
0
好吧,我做到了,这是我的解决方案。它有效。
public class DataList{
@SerializedName("featured")
private List<FeaturedItem> featured;
@SerializedName("products")
private List<ProductsItem> products;
@SerializedName("categories")
private List<CategoriesItem> categories;
@SerializedName("collections")
private List<CollectionsItem> collections;
@SerializedName("shops")
private List<ShopsItem> shops;
@SerializedName("type")
private String type;
@SerializedName("title")
private String title;
public List<FeaturedItem> getFeatured() {
return featured;
}
public void setFeatured(List<FeaturedItem> featured) {
this.featured = featured;
}
public List<ProductsItem> getProducts() {
return products;
}
public void setProducts(List<ProductsItem> products) {
this.products = products;
}
public List<CategoriesItem> getCategories() {
return categories;
}
public void setCategories(List<CategoriesItem> categories) {
this.categories = categories;
}
public List<CollectionsItem> getCollections() {
return collections;
}
public void setCollections(List<CollectionsItem> collections) {
this.collections = collections;
}
public List<ShopsItem> getShops() {
return shops;
}
public void setShops(List<ShopsItem> shops) {
this.shops = shops;
}
public void setType(String type){
this.type = type;
}
public String getType(){
return type;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return title;
}
@Override
public String toString(){
if(type.equals("featured")){
return
"Featured Olanlar{" +
"featured = '" + featured + '\'' +
",type = '" + type + '\'' +
",title = '" + title + '\'' +
"}";
}
else if(type.equals("new_products")){
return
"En Yeni Ürünler{" +
"products = '" + products + '\'' +
",type = '" + type + '\'' +
",title = '" + title + '\'' +
"}";
}
else if(type.equals("categories")){
return
"Kategoriler{" +
"categories = '" + categories + '\'' +
",type = '" + type + '\'' +
",title = '" + title + '\'' +
"}";
}
else if(type.equals("collections")){
return
"Koleksiyonlar{" +
"collections = '" + collections + '\'' +
",type = '" + type + '\'' +
",title = '" + title + '\'' +
"}";
}
else if(type.equals("editor_shops")){
return
"Editör Seçimi Vitrinler{" +
"shops = '" + shops + '\'' +
",type = '" + type + '\'' +
",title = '" + title + '\'' +
"}";
}
else if(type.equals("new_shops")){
return
"En Yeni Vitrinler{" +
"shops = '" + shops + '\'' +
",type = '" + type + '\'' +
",title = '" + title + '\'' +
"}";
}
return null;
}
}
于 2018-12-11T22:03:14.713 回答