【发布时间】:2011-06-15 17:32:12
【问题描述】:
我正在努力学习 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 并为 firstName 或 country 之类的字段名称添加 ExclusionStrategy,但我似乎无法排除某些字段的属性,例如 country.name。
使用方法public boolean shouldSkipField(FieldAttributes fa),FieldAttributes 不包含足够的信息来匹配字段与过滤器,如country.name。
P.S:我想避免注释,因为我想对此进行改进并使用 RegEx 过滤字段。
编辑:我正在尝试看看是否可以模仿Struts2 JSON plugin的行为
使用 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 排除为一种类型。
所以类型是相同的,它是我想要精确定位和排除的对象图中的实际位置。
【问题讨论】:
-
从 2.2 版开始,我仍然无法指定要排除的字段路径。 flexjson.sourceforge.net 感觉是个不错的选择。
-
在my answer 上查看一个非常相似的问题。它基于为某些类型创建自定义
JsonSerializer- 在您的情况下为Country- 然后应用ExclusionStrategy来决定要序列化的字段。
标签: java json serialization gson