GSON Field Naming, auto-call method after instantiation

For example i have class:

public static class News implements Comparable<News>, Parcelable {
        static DateFormat df = new SimpleDateFormat("dd-MM-yyyy");

        @SerializedName("Published")
        public String DateStr;

        MyDate date;

        public void callItAfterInstantiate(){
            if(date == null){
               java.util.Date parsed;
               try {
                   parsed = df.parse(DateStr);
                   date = new MyDate(parsed.getTime());
               } catch (ParseException e) {
                   e.printStackTrace();
               }

            }
        }

        {...}
}

I can instantiate it using GSON:

News news = gson.fromJson(json, News.class);

But date = null;

I need to auto-call callItAfterInstantiate after instantiation. Is it possible? Field MyDate just for example. In real project there is can be another logic that should be auto-calling after creation.

Or the one possible solution is to call method directly after instantiation?

news.callItAfterInstantiate();

Upvotes: 0

Views: 1390

Answers (1)

medhdj
medhdj

Reputation: 1178

Okey, here is 2 ways to do that first one will tell default gson parser how to parse date objects

public static class News implements Comparable<News>, Parcelable {
        public static DateFormat df = new SimpleDateFormat("dd-MM-yyyy");


        @SerializedName("Published")
        Date date;
//.....
}

//then you parse your data like this
final GsonBuilder gsonBuilder = new GsonBuilder();
//use your date pattern 
gsonBuilder.setDateFormat(df.toPattern());
final Gson gson = gsonBuilder.create();
News news = gson.fromJson(json, News.class);

Second solution would be the use of news.callItAfterInstantiate(); for that you must overide the JsonDeserializer a very good tutorial

public class NewsDeserializer implements JsonDeserializer<News> {
    public final static String TAG = "NewsDeserializer";

    @Override
    public News deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        //json object is complete 
        final JsonObject jsonObj = json.getAsJsonObject();
        // Log.i(TAG, jsonObj.toString());
        News news = new News();
        //parse your data here using JsonObject see the documentation it's pretty simple

        news.callItAfterInstantiate();
        return news;
    }
}
//then to parse you data
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(News.class, new NewsDeserializer());
final Gson gson = gsonBuilder.create();
News news = gson.fromJson(json, News.class);

Hope this will help

Upvotes: 3

Related Questions