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

时间:2015-01-28 11:48:33

标签: android gson

例如我有课程:

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

但是date = null;

我需要在实例化后自动调用callItAfterInstantiate。可能吗?例如,字段MyDate。在实际项目中,可能存在另一个应该在创建后自动调用的逻辑。

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

news.callItAfterInstantiate();

1 个答案:

答案 0 :(得分:1)

Okey,这里有两种方法可以告诉默认的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);

希望这会有所帮助