Gson 适配多种日期时间格式转换

为了能够使 Gson 适用各种常见时间格式, Gson 增加了适配器模式来解析 Date,我们只需要增加一个自定义的适配器即可。参考下面示例代码:

通过 GsonBuilder 创建一个多适配器的 gson 对象:

public static void main(String[] args) {
        DateJson dateJson = new DateJson(new Date());
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Date.class, new DateTypeAdapter())  // 默认适配器
                .registerTypeAdapter(Date.class, new CustomDateAdapter(2, 2, Locale.CHINESE))  // yyyy-MM-dd HH:mm:ss
//                .registerTypeAdapter(Date.class, new CustomDateAdapter(0, 0, Locale.CHINESE))  // 2020年11月2日 星期一 上午10时54分01秒 CST
//                .registerTypeAdapter(Date.class, new CustomDateAdapter(0, 1, Locale.CHINESE))  // 2020年11月2日 星期一 上午10时54分34秒
//                .registerTypeAdapter(Date.class, new CustomDateAdapter(0, 3, Locale.CHINESE))  // 2020年11月2日 星期一 上午10:55
                .registerTypeAdapter(Date.class, new CustomDateAdapter(1, 1, Locale.CHINESE))  // 2020年11月2日 上午11时00分58秒
//                .registerTypeAdapter(Date.class, new CustomDateAdapter(1, 2, Locale.CHINESE))  // 2020年11月2日 10:56:01
//                .registerTypeAdapter(Date.class, new CustomDateAdapter(3, 2, Locale.CHINESE))  // 20-11-2 10:56:29
//                .registerTypeAdapter(Date.class, new CustomDateAdapter(2, 2, Locale.ENGLISH))  // Nov 2, 2020 10:46:51 AM
//                .registerTypeAdapter(Date.class, new CustomDateAdapter(2, 2, Locale.US))       // Nov 2, 2020 10:46:51 AM
                .registerTypeAdapter(Date.class, new CustomDateAdapter(2, 2, Locale.getDefault())) // 根据服务器不一样而不一样
                .create();

        LOGGER.info("{}", gson.toJson(dateJson));
    }

自定义适配器:

/**
 * @author ouyang
 * @version 1.0
 **/
public class CustomDateAdapter extends TypeAdapter<Date> {

    private final List<DateFormat> dateFormats = new ArrayList<>();

    /**
     * Creates a DateFormat with the given time and/or date style in the given
     * locale.
     * @param timeStyle a value from 0 to 3 indicating the time format,
     * ignored if flags is 2
     * @param dateStyle a value from 0 to 3 indicating the time format,
     * ignored if flags is 1
     * @param aLocale the locale for the format
     */
    public CustomDateAdapter(int dateStyle, int timeStyle, Locale aLocale) {
        this.dateFormats.add(DateFormat.getDateTimeInstance(dateStyle, timeStyle, aLocale));
    }

    public Date read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        } else {
            return this.deserializeToDate(in.nextString());
        }
    }

    private synchronized Date deserializeToDate(String json) {
        for (DateFormat dateFormat : this.dateFormats) {
            try {
                return dateFormat.parse(json);
            } catch (ParseException ignored) {
            }
        }

        try {
            return ISO8601Utils.parse(json, new ParsePosition(0));
        } catch (ParseException var5) {
            throw new JsonSyntaxException(json, var5);
        }
    }

    public synchronized void write(JsonWriter out, Date value) throws IOException {
        if (value == null) {
            out.nullValue();
        } else {
            String dateFormatAsString = this.dateFormats.get(0).format(value);
            out.value(dateFormatAsString);
        }
    }
}

简单演示对象:

/**
 * @author ouyang
 * @version 1.0
 **/
public class DateJson {
    private Date timestamp;

    public DateJson() {
    }

    public DateJson(Date timestamp) {
        this.timestamp = timestamp;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    @Override
    public String toString() {
        return "DateJson{" +
                "timestamp=" + timestamp +
                '}';
    }
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lytao123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值