有什么原因无法将匿名类序列化为 Json 吗?
Example:
public class AnonymousTest
{
private Gson gson = new Gson();
public void goWild()
{
this.callBack(new Result()
{
public void loginResult(Result loginAttempt)
{
// Output null
System.out.println(this.gson.toJson(result));
}
});
}
public void callBack(Result result)
{
// Output null
System.out.println(this.gson.toJson(result));
result.loginResult(result);
}
public static void main(String[] args)
{
new AnonymousTest().goWild();
}
}
刚刚开始使用它:)
用户指南中对此进行了解释:https://sites.google.com/site/gson/gson-user-guide https://sites.google.com/site/gson/gson-user-guide
Gson 还可以反序列化静态嵌套类。然而,Gson 不能
自动反序列化纯内部类,因为它们无参数
构造函数还需要对包含对象的引用,即
反序列化时不可用。
您可以通过使类成为非匿名和静态来修复代码:
static class MyResult extends Result {
public void loginResult(Result loginAttempt) {
System.out.println(new Gson().toJson(result));
}
}
...
this.callBack(new MyResult());
请注意,您不能使用外部类中的 gson 字段,您必须创建一个新字段或从其他地方获取它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)