问题描述
我有一个名为 PageItem
类,它有一个构造函数一个上下文
作为参数:
I have a class named PageItem
, which has a constructor that takes a Context
as parameter:
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
和主题
其他类我的应用程序,并有下面的构造函数:
Newsprovider
and Topic
are other classes of my application and have the following constructors:
Newsprovider (Context context)
{
super(context);
this.context = context;
}
Topic (Context context)
{
super(context);
this.context = context;
}
PageItem
, Newsprovider
和主题
是子类 SQLiteOpenHelper
。
我要反序列化与GSON PageItem
阵列,所以我写了:
I want to deserialize PageItem
array with Gson, so I wrote:
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。
When debugging, a PageItem
instance has correctly "MainActivity" as context whilebut its newsprovider
member variable has context = null.
GSON创建使用正确的构造 PageItem
对象,但它使用默认参数的构造函数创建 Newsprovider
实例。我该如何解决这个问题?
Gson created PageItem
object using the right constructor but it created Newsprovider
instance using the default parameterless constructor. How can I fix this?
推荐答案
只需添加一个新的 InstanceCreator
派生类 NewsProvider
是这样的:
Just add a new InstanceCreator
derived class for NewsProvider
like this:
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
像你已经这样做,是这样的:
and register it into the GsonBuilder
like you have already done, like this:
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);
重复它也为主题
类。
这篇关于GSON反序列化与InstanceCreator嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!