我正在努力学习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;
}
Run Code Online (Sandbox Code Playgroud)
我可以使用GsonBuilder并添加ExclusionStrategy像一个字段名称firstName或country,但我似乎无法管理排除像某些领域的性能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, …Run Code Online (Sandbox Code Playgroud) Gson用户指南声明我们应该为任何类定义默认的no-args构造函数以正确使用Gson.更重要的是,在Gson 类的javadoc中,InstanceCreator如果我们尝试反序列化缺少默认构造函数的类的实例,那么将抛出异常,我们应该InstanceCreator在这种情况下使用.但是,我尝试使用缺少默认构造函数的类来测试使用Gson,并且序列化和反序列化工作都没有任何问题.
这是deserializaiton的一段代码.没有非args构造函数的类:
public class Mushroom {
private String name;
private double diameter;
public Mushroom(String name, double diameter) {
this.name = name;
this.diameter = diameter;
}
//equals(), hashCode(), etc.
}
Run Code Online (Sandbox Code Playgroud)
和测试:
@Test
public void deserializeMushroom() {
assertEquals(
new Mushroom("Fly agaric", 4.0),
new Gson().fromJson(
"{name:\"Fly agaric\", diameter:4.0}", Mushroom.class));
}
Run Code Online (Sandbox Code Playgroud)
哪个工作正常.
所以我的问题是:我是否真的可以使用Gson而不需要默认构造函数,或者在任何情况下它都不起作用?