2

我正在尝试使用 gson 将作为 JSON (StartDate=/Date(1341348517698+0200)/) 的 DateTime (C#) 反序列化为 Android Calendar 对象...

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

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

3 回答 3

6

您需要为 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);
于 2012-07-03T22:07:24.297 回答
1

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

于 2012-07-03T21:31:41.113 回答
1
/**
 * 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);
于 2019-03-29T02:19:11.100 回答