Gson deserializing nested objects with InstanceCreator

流过昼夜 提交于 2019-12-18 04:37:12

问题


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 has these properties:

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

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 and Topic are subclasses of SQLiteOpenHelper.

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

with PageItemInstanceCreator defined as:

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; 
        }
}

When debugging, a PageItem instance has correctly "MainActivity" as context while but its newsprovider member variable has context = null.

Gson created PageItem object using the right constructor but it created Newsprovider instance using the default parameterless constructor. How can I fix this?


回答1:


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; 
        }

}

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

repeat it also for Topic class.



来源:https://stackoverflow.com/questions/18567719/gson-deserializing-nested-objects-with-instancecreator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!