Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing anonymous classes with 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 :)

like image 723
Lucas Arrefelt Avatar asked May 24 '12 22:05

Lucas Arrefelt


1 Answers

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.

like image 195
TimK Avatar answered Oct 09 '22 06:10

TimK