Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson deserializing nested objects with InstanceCreator

Tags:

java

android

gson

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?

like image 390
user2568379 Avatar asked Sep 02 '13 07:09

user2568379


1 Answers

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.

like image 155
giampaolo Avatar answered Sep 23 '22 08:09

giampaolo