gson:convert / Date(1341348517698 + 0200)/到日历

时间:2012-07-03 21:28:41

标签: android json calendar gson

我正在尝试使用gson将日期时间(C#)反序列化为JSON(StartDate = / Date(1341348517698 + 0200)/)到Android日历对象...

我已经尝试了以下但没有成功:

ObjectWithCalender cal = gson.fromJson(jsonWithDate, ObjectWithCalender.class);

3 个答案:

答案 0 :(得分:5)

您需要为Date创建自定义反序列化程序。例如创建这个类:

public class DotNetDateDeserializer implements JsonDeserializer<Date> {
   @Override
   public Date deserialize(JsonElement json, Type typfOfT, JsonDeserializationContext context) {
      // this is the place where you convert .NET timestamp into Java Date object
   } 
}

然后在将JSON字符串转换为POJO之前:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new DotNetDateDeserializer());
Gson gson = builder.create();
gson.fromJson(jsonString, Class);

答案 1 :(得分:1)

使用unix时间戳而不是datetime,datetime是不明确的struct

答案 2 :(得分:0)

/**
 * The Class CalendarFromTimestampJsonDeserializer.
 */
    public class CalendarFromTimestampJsonDeserializer implements JsonDeserializer<Calendar>{

        /* (non-Javadoc)
         * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, com.google.gson.JsonDeserializationContext)
         */
        public Calendar deserialize(JsonElement json, Type typeOfT,
                JsonDeserializationContext context) throws JsonParseException {
            long timestamp = json.getAsLong();
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(timestamp);
            return calendar;
        }
    }

然后

GsonBuilder builder = new GsonBuilder();
            builder.registerTypeAdapter(Calendar.class, new CalendarFromTimestampJsonDeserializer());
            Gson gson = builder.create();

在列表的情况下

List<ObjectWithCalendar> objList = gson.fromJson(objectJsonArray.toString(), new TypeToken<List<ObjectWithCalendar>>(){}.getType());

或其他对象

ObjectWithCalendar obj = gson.fromJson(objectJson.toString(), ObjectWithCalendar.class);