Gson 使用 InstanceCreator 反序列化嵌套对象

2022-09-03 14:48:38

我有一个名为 的类,它有一个构造函数,它接受一个 as 参数:PageItemContext

PageItem(Context context)
{
    super(context);
    this.context = context;
}

PageItem具有以下属性:

private int id; 
private String Title; 
private String Description; 
public Newsprovider newsprovider; 
public Topic topic;

Newsprovider并且是我的应用程序的其他类,并具有以下构造函数:Topic

Newsprovider (Context context)
{
    super(context);
    this.context = context;
}

Topic (Context context)
{
    super(context);
    this.context = context;
}

PageItem,并且是 的子类。NewsproviderTopicSQLiteOpenHelper

我想用Gson反序列化数组,所以我写了:PageItem

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(PageItem.class, new PageItemInstanceCreator(context));
Gson gson = gsonBuilder.create();
Pageitem pis[] = gson.fromJson(s, PageItem[].class);

定义为:PageItemInstanceCreator

public class PageItemInstanceCreator implements InstanceCreator<PageItem>
    {
        private Context context;

        public PageItemInstanceCreator(Context context)
        {
            this.context = context;
        }

        @Override
        public PageItem createInstance(Type type)
        {
            PageItem pi = new PageItem(context);
            return pi; 
        }
}

调试时,实例具有正确的“MainActivity”作为上下文,而其成员变量具有上下文 = null。PageItemnewsprovider

Gson使用正确的构造函数创建了对象,但它使用默认的无参数构造函数创建了实例。我该如何解决这个问题?PageItemNewsprovider


答案 1

只需添加一个新的派生类,如下所示:InstanceCreatorNewsProvider

public class NewsProviderInstanceCreator implements InstanceCreator<NewsProvider>
    {
        private int context;

        public NewsProviderInstanceCreator(int context)
        {
            this.context = context;
        }

        @Override
        public NewsProvider createInstance(Type type)
        {
            NewsProvider np = new NewsProvider(context);
            return np; 
        }

}

并将其注册到您已经完成的类似操作中,如下所示:GsonBuilder

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(PageItem.class, new PageItemInstanceCreator(context));
gsonBuilder.registerTypeAdapter(NewsProvider.class, new NewsProviderInstanceCreator(context));
Gson gson = gsonBuilder.create();
PageItem pis[] = gson.fromJson(s, PageItem[].class);

在课堂上也重复一遍。Topic


答案 2

推荐