GsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss")
为仅日期字段附加 00:00:00。
有什么方法可以覆盖此行为,因为要求是仅显示日期以及带时间的日期。
最佳答案
如果您将“日期”定义为 java.util.Date
,其中小时、分钟和秒都为零,而“日期与时间”定义为 Date
,其中他们不是。你可以做这样的事情:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new CustomDateJsonSerializer());
用 CustomDateJsonSerializer
定义如下:
public class CustomDateJsonSerializer implements JsonSerializer<Date>, JsonDeserializer<Date> {
private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC");
private static final Pattern DATE_PATTERN = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
private static final Pattern DATE_TIME_PATTERN = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}");
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String asString = json.getAsString();
try {
if (DATE_PATTERN.matcher(asString).matches()) {
return getDateFormat().parse(asString);
} else if (DATE_TIME_PATTERN.matcher(asString).matches()) {
return getDateTimeFormat().parse(asString);
} else {
throw new JsonParseException("Could not parse to date: " + json);
}
} catch (ParseException e) {
throw new JsonParseException("Could not parse to date: " + json, e);
}
}
private static DateFormat getDateFormat() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd");
simpleDateFormat.setTimeZone(UTC_TIME_ZONE);
return simpleDateFormat;
}
private static DateFormat getDateTimeFormat() {
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
dateFormat.setTimeZone(UTC_TIME_ZONE);
return dateFormat;
}
public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) {
Calendar calendar = Calendar.getInstance(UTC_TIME_ZONE);
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
String dateFormatted;
if (hours == 0 && minutes == 0 && seconds == 0) {
dateFormatted = getDateFormat().format(date);
} else {
dateFormatted = getDateTimeFormat().format(date);
}
return new JsonPrimitive(dateFormatted);
}
}
关于java - GSON:有没有办法在编码时返回两种不同的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26606477/