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
Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With