RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1239979
Accepted
Elizaveta
Elizaveta
Asked:2022-02-04 22:19:19 +0000 UTC2022-02-04 22:19:19 +0000 UTC 2022-02-04 22:19:19 +0000 UTC

Gson + List<> 如何序列化层次结构

  • 772

我有以下层次结构:

产品:

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)但这来到了前面{}

java
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. Best Answer
    ЮрийСПб
    2022-02-04T22:47:23Z2022-02-04T22:47:23Z

    您的 Catalog 类中没有 Expose 注释。因此,Json 是空的,因为。您已明确阻止在没有此注释的情况下对字段进行序列化。有必要删除此禁令或添加注释

    • 1
  2. Elizaveta
    2022-02-04T22:37:54Z2022-02-04T22:37:54Z

    结果比我想象的要容易 - 我只需要在文档中爬一点。希望它可以帮助某人!)

    import coherentsolutions.nastyabakhshieva.model.catalog.Catalog;
    import coherentsolutions.nastyabakhshieva.model.categories.Category;
    import com.google.gson.TypeAdapter;
    import com.google.gson.stream.JsonReader;
    import com.google.gson.stream.JsonWriter;
    import lombok.extern.slf4j.Slf4j;
    
    import java.io.IOException;
    
    @Slf4j
    public class CatalogTypeAdapter extends TypeAdapter<Catalog> {
    
        @Override
        public void write(JsonWriter jsonWriter, Catalog catalog) throws IOException {
            jsonWriter.beginObject();
            jsonWriter.name("categories");
            jsonWriter.beginArray();
    
            for (Category category : catalog.getCategories()) {
                jsonWriter.beginObject();
                jsonWriter.name("id");
                jsonWriter.value(category.getId());
                jsonWriter.name("title");
                jsonWriter.value(category.getTitle());
                jsonWriter.name("products");
    
                jsonWriter.beginArray();
                category.getProducts().forEach(product -> {
                    try {
                        jsonWriter.beginObject();
    
                        jsonWriter.name("id");
                        jsonWriter.value(product.getId());
                        jsonWriter.name("name");
                        jsonWriter.value(product.getName());
                        jsonWriter.name("price in cents");
                        jsonWriter.value(product.getPriceInCents());
                        jsonWriter.name("rate");
                        jsonWriter.value(product.getRate());
    
                        jsonWriter.endObject();
    
                    } catch (IOException e) {
                        log.error("IN write - {}", e.getMessage());
                    }
                });
                jsonWriter.endArray();
    
                jsonWriter.endObject();
            }
    
            jsonWriter.endArray();
            jsonWriter.endObject();
        }
    
        @Override
        public Catalog read(JsonReader jsonReader) throws IOException {
            //do nothing
            return null;
        }
    }
    

    控制台输出:

    {
      "categories": [
        {
          "id": 1,
          "title": "Clothes category",
          "products": [
            {
              "id": 1,
              "name": "Sweater",
              "price in cents": 65458,
              "rate": 45
            },
            {
              "id": 2,
              "name": "Jacket",
              "price in cents": 11111,
              "rate": 89
            },
            {
              "id": 3,
              "name": "Coat",
              "price in cents": 9999,
              "rate": 36
            },
            {
              "id": 4,
              "name": "Vest",
              "price in cents": 1200,
              "rate": 68
            },
            {
              "id": 5,
              "name": "Shorts",
              "price in cents": 45000,
              "rate": 90
            },
            {
              "id": 6,
              "name": "Casual dress",
              "price in cents": 36500,
              "rate": 79
            }
          ]
        },
        {
          "id": 2,
          "title": "Food category",
          "products": [
            {
              "id": 7,
              "name": "Meet",
              "price in cents": 2132,
              "rate": 100
            },
            {
              "id": 8,
              "name": "Cookies",
              "price in cents": 1111,
              "rate": 90
            },
            {
              "id": 9,
              "name": "Bread",
              "price in cents": 777,
              "rate": 85
            },
            {
              "id": 10,
              "name": "Apples",
              "price in cents": 454,
              "rate": 32
            },
            {
              "id": 11,
              "name": "Ice cream",
              "price in cents": 873,
              "rate": 79
            }
          ]
        },
        {
          "id": 3,
          "title": "Toys category",
          "products": [
            {
              "id": 13,
              "name": "Barbie",
              "price in cents": 12345,
              "rate": 80
            },
            {
              "id": 14,
              "name": "Cycle",
              "price in cents": 65432,
              "rate": 90
            },
            {
              "id": 15,
              "name": "Lorry",
              "price in cents": 10000,
              "rate": 55
            },
            {
              "id": 16,
              "name": "Little hare",
              "price in cents": 6400,
              "rate": 97
            },
            {
              "id": 17,
              "name": "Bricks",
              "price in cents": 1500,
              "rate": 100
            },
            {
              "id": 18,
              "name": "Rocking horse",
              "price in cents": 10999,
              "rate": 10
            }
          ]
        }
      ]
    }
    
    • 0

相关问题

  • wpcap 找不到指定的模块

  • 如何以编程方式从桌面应用程序打开 HTML 页面?

  • Android Studio 中的 R.java 文件在哪里?

  • HashMap 初始化

  • 如何使用 lambda 表达式通过增加与原点的距离来对点进行排序?

  • 最大化窗口时如何调整元素大小?

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    表格填充不起作用

    • 2 个回答
  • Marko Smith

    提示 50/50,有两个,其中一个是正确的

    • 1 个回答
  • Marko Smith

    在 PyQt5 中停止进程

    • 1 个回答
  • Marko Smith

    我的脚本不工作

    • 1 个回答
  • Marko Smith

    在文本文件中写入和读取列表

    • 2 个回答
  • Marko Smith

    如何像屏幕截图中那样并排排列这些块?

    • 1 个回答
  • Marko Smith

    确定文本文件中每一行的字符数

    • 2 个回答
  • Marko Smith

    将接口对象传递给 JAVA 构造函数

    • 1 个回答
  • Marko Smith

    正确更新数据库中的数据

    • 1 个回答
  • Marko Smith

    Python解析不是css

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5