8

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 :)

Lucas Arrefelt
  • 3,879
  • 5
  • 41
  • 71

1 Answers1

8

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.

TimK
  • 4,635
  • 2
  • 27
  • 27
  • Ah I totally missed out on that one. Thanks a lot! – Lucas Arrefelt May 27 '12 at 19:56
  • 7
    That quote is in reference to deserialization and not serialization. And sure, that makes sense for deserialization, but not for serialization. It shouldn't matter to the serializer that it's an inner class, it doesn't need the reference to the outer class just to get its values. – Jeff Mercado Jun 09 '17 at 17:41