我有以下层次结构:
产品:
import com.google.gson.annotations.Expose;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
@Data
@NoArgsConstructor
public class Product implements Serializable {
private static final AtomicLong counter = new AtomicLong(1L);
@Expose
private long id;
@Expose
private String name;
@Expose
private long priceInCents;
@Expose
private int rate;
public Product(String name, long priceInCents, int rate) {
this.id = counter.getAndIncrement();
this.name = name;
this.priceInCents = priceInCents;
this.rate = rate;
}
public Product(long id, String name, long priceInCents, int rate) {
this.id = id;
this.name = name;
this.priceInCents = priceInCents;
this.rate = rate;
}
public Product(long id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return id == product.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
产品类别:
import coherentsolutions.nastyabakhshieva.model.products.Product;
import com.google.gson.annotations.Expose;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
@Data
public abstract class Category implements Serializable {
private static final AtomicLong counter = new AtomicLong(1L);
@Expose
protected long id;
@Expose
protected String title;
@Expose
protected List<Product> products;
public Category(long id) {
this.id = id;
}
public Category() {
this.id = counter.getAndIncrement();
}
@Override
public String toString() {
return "Category{" +
"title='" + title + '\'' +
", products=" + products +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Category category = (Category) o;
return id == category.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
还有一个包含所有类别的目录:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Catalog implements Serializable {
private List<Category> categories;
}
我知道可以为列表获取适配器 ---> Type itemsListType = new TypeToken<List<GoodsItem>>() {}.getType();
,但我的情况并不完全相同(请帮助,我该如何发送?
我也尝试通过方法简单地序列化,gson.toJson(catalog)
但这来到了前面{}
您的 Catalog 类中没有 Expose 注释。因此,Json 是空的,因为。您已明确阻止在没有此注释的情况下对字段进行序列化。有必要删除此禁令或添加注释
结果比我想象的要容易 - 我只需要在文档中爬一点。希望它可以帮助某人!)
控制台输出: