java - GSON:有没有办法在编码时返回两种不同的日期格式

标签 java gson marshalling

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/

相关文章:

java - 如何更改不同 fragment 中的选项菜单?

java - 有什么方法可以使用 Apache POI 读取 .xls 和 .xlsx 文件吗?

java - 具有特定格式的 XMLGregorianCalendar 日期

java - Gson序列化: can I do it from the JSON String or I need to use JsonWriter?

java - 如何用Gson解析响应

c# - MarshalAs 属性案例研究

java - 构建使用 opencv 可移植的 java 应用程序

java - Gson反序列化跳过一引号

python - 如何将上下文传递给 Marshmallow 中的嵌套序列化程序?

c# - 从 C# 调用 C DLL 导致尝试读取或写入 protected 内存