问题描述
示例:
<$ p $有没有任何理由说明你为什么不能将匿名类序列化为Json? public class AnonymousTest
{
private Gson gson = new Gson();
$ b public void goWild()
{
this.callBack(new Result()
{
public void loginResult(result loginAttempt)
{
//输出null
System.out.println(this.gson.toJson(result));
}
});
}
public void callBack(结果结果)
{
//输出null
System.out.println(this.gson.toJson(result ));
result.loginResult(result);
public static void main(String [] args)
{
new AnonymousTest()。goWild();
刚开始使用它:)
在用户指南中进行了解释:
您可以通过让您的类非匿名和静态来修复您的代码:
<$ p (); $ p $ static class MyResult extends Result {
public void loginResult(Result loginAttempt){
System.out.println(new Gson()。toJson(result));
}
}
...
this.callBack(new MyResult());
请注意,您无法使用外部类的gson字段,您必须创建一个新的一个或从别的地方得到它。
Is there any reason to why you cant serialize anonymous classes to 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();
}
}
Just getting started with it :)
It is explained in the user guide: https://sites.google.com/site/gson/gson-user-guide
You can fix your code by making your class non-anonymous and static:
static class MyResult extends Result {
public void loginResult(Result loginAttempt) {
System.out.println(new Gson().toJson(result));
}
}
...
this.callBack(new MyResult());
Note that you can't use the gson field from the outer class, you have to make a new one or get it from somewhere else.
这篇关于使用Gson序列化匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!