【问题标题】:How to exclude certain attributes from being serialized如何排除某些属性被序列化
【发布时间】:2021-04-19 17:54:12
【问题描述】:

这个问题已经被问过很多次了,我有一个 Java POJO 类,我想通过排除一些属性来序列化它。为了做到这一点,我使用了 GSON 的 @Expose。问题是它似乎不起作用。

即使我使用这个:Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

它不起作用。

我不愿意使用瞬态,因为它会禁用给定属性的序列化和反序列化。

【问题讨论】:

    标签: java spring gson


    【解决方案1】:

    你可以使用瞬态

    private transient String property;
    

    【讨论】:

    • 我希望能够反序列化它。
    【解决方案2】:

    确保正确初始化 Gson 对象。如果你想使用 Exclude 注解,你应该在你的 GsonBuilder 中调用 excludeFieldsWithoutExposeAnnotation 方法。

    例如 Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

    Gson javadoc description of excludeFieldsWithoutExposeAnnotation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2020-02-22
      • 2011-01-27
      • 1970-01-01
      • 2013-02-05
      相关资源
      最近更新 更多