Serializing anonymous classes with Gson

最后都变了- 提交于 2019-12-06 23:20:08

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/10746278/serializing-anonymous-classes-with-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!