我正在尝试学习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来排除字段名称,例如
firstName
或country
,但是似乎无法排除某些字段的属性,例如country.name
。使用方法
public boolean shouldSkipField(FieldAttributes fa)
,FieldAttributes不包含足够的信息来将该字段与过滤器(例如country.name
)匹配。附言:我想避免使用注释,因为我想改进并使用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作为类型。
因此,类型是相同的,实际上是我想要确定并排除对象图中的位置。
JsonSerializer
对某种类型(比如你的情况中的Country
)进行序列化时应用一个ExclusionStrategy
,以决定哪些字段需要序列化。 - pirho