java 使用两个 DateFormat 进行 Gson 到 json 的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15563155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Gson to json conversion with two DateFormat
提问by wangyif2
My server JSON is returning with two different type of DateFormat. "MMM dd, yyyy" and "MMM dd, yyyy HH:mm:ss"
我的服务器 JSON 返回了两种不同类型的 DateFormat。“MMM dd,yyyy”和“MMM dd,yyyy HH:mm:ss”
When I convert the JSON with the following it is fine:
当我使用以下内容转换 JSON 时,它很好:
Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy").create();
But when I want the detailed date format and changed it to this, it throws exception com.google.gson.JsonSyntaxException: Mar 21, 2013
但是当我想要详细的日期格式并将其更改为此时,它会抛出异常 com.google.gson.JsonSyntaxException: Mar 21, 2013
Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy HH:mm:ss").create();
Is there a way for gson to handle two different DateFormat for its Json conversion?
gson 有没有办法为其 Json 转换处理两种不同的 DateFormat?
回答by andrew
I was facing the same issue. Here is my solution via custom deserialization:
我面临同样的问题。这是我通过自定义反序列化的解决方案:
new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer());
private static final String[] DATE_FORMATS = new String[] {
"MMM dd, yyyy HH:mm:ss",
"MMM dd, yyyy"
};
private class DateDeserializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF,
JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
} catch (ParseException e) {
}
}
throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
+ "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
}
}
回答by JRomero
Although the answer has been accepted I wanted to share a similar yet more extensible solution. You can find the gist here.
虽然答案已被接受,但我想分享一个类似但更具扩展性的解决方案。你可以在这里找到要点。
DateDeserializer.java
日期解串器.java
public class DateDeserializer<T extends Date> implements JsonDeserializer<T> {
private static final String TAG = DateDeserializer.class.getSimpleName();
private final SimpleDateFormat mSimpleDateFormat;
private final Class<T> mClazz;
public DateDeserializer(SimpleDateFormat simpleDateFormat, Class<T> clazz) {
mSimpleDateFormat = simpleDateFormat;
mClazz = clazz;
}
@Override
public T deserialize(JsonElement element, Type arg1, JsonDeserializationContext context) throws JsonParseException {
String dateString = element.getAsString();
try {
T date = mClazz.newInstance();
date.setTime(mSimpleDateFormat.parse(dateString).getTime());
return date;
} catch (InstantiationException e) {
throw new JsonParseException(e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new JsonParseException(e.getMessage(), e);
} catch (ParseException e) {
throw new JsonParseException(e.getMessage(), e);
}
}
}
Then register the different formats as...
然后将不同的格式注册为...
sGson = new GsonBuilder()
.registerTypeAdapter(Event.EventDateTime.class,
new DateDeserializer<Event.EventDateTime>(
Event.EventDateTime.DATE_FORMAT, Event.EventDateTime.class))
.registerTypeAdapter(Event.StartEndDateTime.class,
new DateDeserializer<Event.StartEndDateTime>(
Event.StartEndDateTime.DATE_FORMAT, Event.StartEndDateTime.class))
.registerTypeAdapter(Event.SimpleDate.class,
new DateDeserializer<Event.SimpleDate>(
Event.SimpleDate.DATE_FORMAT, Event.SimpleDate.class))
.create();
Each format is then mapped to a class...
然后将每种格式映射到一个类...
public class Event {
@SerializedName("created")
private EventDateTime mCreated;
//@SerializedName("updated")
private EventDateTime mUpdated;
...
@SerializedName("start")
private ConditionalDateTime mStart;
@SerializedName("end")
private ConditionalDateTime mEnd;
public static class ConditionalDateTime {
@SerializedName("dateTime")
private StartEndDateTime mDateTime;
@SerializedName("date")
private SimpleDate mDate;
public SimpleDate getDate() {
return mDate;
}
public StartEndDateTime getDateTime() {
return mDateTime;
}
/**
* If it is an all day event then only date is populated (not DateTime)
* @return
*/
public boolean isAllDayEvent() {
return mDate != null;
}
}
public static class EventDateTime extends Date {
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
}
public static class StartEndDateTime extends Date {
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
}
public static class SimpleDate extends java.util.Date {
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
}
}
回答by Programmer Bruce
Custom deserialization is necessary. A decent solution would be to make use of the Apache Commons DateUtil, which can handle multiple date formats at once. Also, the JodaTime API might have a similar feature.
自定义反序列化是必要的。一个不错的解决方案是使用 Apache Commons DateUtil,它可以一次处理多种日期格式。此外,JodaTime API 可能具有类似的功能。