Gson:如何在没有注释的情况下从序列化中排除特定字段

新手上路,请多包涵

我正在尝试学习 Gson,但我正在努力解决字段排除问题。这是我的课

public class Student {
  private Long                id;
  private String              firstName        = "Philip";
  private String              middleName       = "J.";
  private String              initials         = "P.F";
  private String              lastName         = "Fry";
  private Country             country;
  private Country             countryOfBirth;
}

public class Country {
  private Long                id;
  private String              name;
  private Object              other;
}

我可以使用 GsonBuilder 并为字段名称添加 ExclusionStrategy,例如 firstNamecountry 但我似乎无法排除某些字段的属性,例如 country.name

使用方法 public boolean shouldSkipField(FieldAttributes fa) , FieldAttributes 不包含足够的信息来匹配字段与过滤器 country.name

PS:我想避免注释,因为我想对此进行改进并使用 RegEx 过滤字段。

编辑:我正在尝试查看是否可以模拟 Struts2 JSON 插件 的行为

使用 Gson

 <interceptor-ref name="json">
  <param name="enableSMD">true</param>
  <param name="excludeProperties">
    login.password,
    studentList.*\.sin
  </param>
</interceptor-ref>

编辑: 我重新打开了这个问题,并添加了以下内容:

我添加了第二个具有相同类型的字段以进一步澄清这个问题。基本上我想排除 country.name 但不是 countrOfBirth.name 。我也不想将 Country 排除为一种类型。所以类型是相同的,它是我想要查明和排除的对象图中的实际位置。

原文由 Liviu T. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 599
1 个回答

任何您不想序列化的字段通常都应该使用“transient”修饰符,这也适用于 json 序列化程序(至少它适用于我使用过的一些序列化程序,包括 gson)。

如果您不希望 name 出现在序列化的 json 中,请给它一个 transient 关键字,例如:

 private transient String name;

Gson 文档中的更多详细信息

原文由 Chris Seline 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题