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

我有一个名为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; 

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

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

PageItemNewsproviderTopicSQLiteOpenHelper子类。

我想用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; } } 

debugging时, PageItem实例正确地将“MainActivity”作为上下文,但其newsprovider成员variables的context = null。

Gson使用正确的构造函数创build了PageItem对象,但它使用默认的无参数构造函数创build了Newsprovider实例。 我怎样才能解决这个问题?

Solutions Collecting From Web of "Gson使用InstanceCreator反序列化嵌套的对象"

只需像这样为NewsProvider添加一个新的InstanceCreator派生类:

 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类。