Gson: How to exclude specific fields from Serialization without annotations

问题:

I'm trying to learn Gson and I'm struggling with field exclusion.我正在尝试学习 Gson,但我正在努力解决字段排除问题。 Here are my classes这是我的课

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;
}

I can use the GsonBuilder and add an ExclusionStrategy for a field name like firstName or country but I can't seem to manage to exclude properties of certain fields like country.name .我可以使用 GsonBuilder 并为字段名称(如firstNamecountry添加 ExclusionStrategy ,但我似乎无法排除某些字段(如country.name属性。

Using the method public boolean shouldSkipField(FieldAttributes fa) , FieldAttributes doesn't contain enough information to match the field with a filter like country.name .使用public boolean shouldSkipField(FieldAttributes fa) ,FieldAttributes 不包含足够的信息来匹配字段与像country.name这样的过滤器。

PS: I want to avoid annotations since I want to improve on this and use RegEx to filter fields out. PS:我想避免注释,因为我想对此进行改进并使用 RegEx 过滤字段。

Edit : I'm trying to see if it's possible to emulate the behavior of Struts2 JSON plugin编辑:我正在尝试查看是否可以模拟Struts2 JSON 插件的行为

using Gson使用 Gson

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

Edit: I reopened the question with the following addition:编辑:我用以下补充重新打开了这个问题:

I added a second field with the same type to futher clarify this problem.我添加了具有相同类型的第二个字段以进一步阐明这个问题。 Basically I want to exclude country.name but not countrOfBirth.name .基本上我想排除country.name但不是countrOfBirth.name I also don't want to exclude Country as a type.我也不想排除 Country 作为一种类型。 So the types are the same it's the actual place in the object graph that I want to pinpoint and exclude.所以类型是相同的,它是我想要查明和排除的对象图中的实际位置。


解决方案:

参考一: https://en.stackoom.com/question/K9Rv
参考二: https://stackoom.com/question/K9Rv
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章