我有一个名为PageItem
的类,该类具有一个将Context
作为参数的构造函数:
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
,Newsprovider
和Topic
是SQLiteOpenHelper
的子类。我想用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;
}
}
调试时,
PageItem
实例将正确的“MainActivity”作为上下文,而但其
newsprovider
成员变量的上下文为null。Gson使用正确的构造函数创建了
PageItem
对象,但使用默认的无参数构造函数创建了Newsprovider
实例。我怎样才能解决这个问题? 最佳答案
只需为InstanceCreator
添加一个新的NewsProvider
派生类,如下所示:
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
类也重复同样的步骤。