使用Gson序列化匿名类 [英] Serializing anonymous classes with Gson

查看:115
本文介绍了使用Gson序列化匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:

<$ 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();


刚开始使用它:)

解决方案

在用户指南中进行了解释: https://sites.google.com/site/gson/gson-user-guide


Gson也可以反序列化静态嵌套类。但是,Gson不能
自动反序列化纯内部类,因为它们的无参数
构造函数也需要对包含对象的引用,这是
在反序列化时不可用。


您可以通过让您的类非匿名和静态来修复您的代码:

<$ 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

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.

这篇关于使用Gson序列化匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆