GSON Field Naming,实例化后自动调用方法

GSON Field Naming, auto-call method after instantiation

例如我有 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();
               }

            }
        }

        {...}
}

我可以使用 GSON 实例化它:

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

但是日期 = null;

我需要在实例化后自动调用 callItAfterInstantiate。可能吗?字段 MyDate 仅作为示例。在实际项目中,可以有另一种逻辑,应该在创建后自动调用。

或者一种可能的解决方案是实例化后直接调用方法?

news.callItAfterInstantiate();

好的,这里有两种方法,第一种会告诉默认的 gson 解析器如何解析日期对象

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

第二种解决方案是使用 news.callItAfterInstantiate(); 因为你必须覆盖 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);

希望这会有所帮助