GSON - 日期格式 [英] GSON - Date format

查看:29
本文介绍了GSON - 日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Gson 输出中使用自定义日期格式,但是 .setDateFormat(DateFormat.FULL) 似乎不起作用,它与 .registerTypeAdapter(Date.class, new DateSerializer()).

I'm trying to have a custom date format in Gson output, but .setDateFormat(DateFormat.FULL) doesn't seem to work and it the same with .registerTypeAdapter(Date.class, new DateSerializer()).

就像 Gson 不关心对象Date"并以它的方式打印它.

It's like Gson doesn't care about the object "Date" and print it in its way.

我该如何改变?

谢谢

@Entity
public class AdviceSheet {
  public Date lastModif;
[...]
}

public void method {
   Gson gson = new GsonBuilder().setDateFormat(DateFormat.LONG).create();
   System.out.println(gson.toJson(adviceSheet);
}

我总是使用 java.util.Date;setDateFormat() 不起作用 :(

I always use java.util.Date; setDateFormat() doesn't work :(

推荐答案

看来您需要为日期和时间部分定义格式或使用基于字符串的格式.例如:

It seems that you need to define formats for both date and time part or use String-based formatting. For example:

Gson gson = new GsonBuilder()
   .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();

使用 java.text.DateFormat

Gson gson = new GsonBuilder()
   .setDateFormat(DateFormat.FULL, DateFormat.FULL).create();

或者用序列化器来做:

我相信格式化程序不能产生时间戳,但是这个序列化器/反序列化器对似乎可以工作

I believe that formatters cannot produce timestamps, but this serializer/deserializer-pair seems to work

JsonSerializer<Date> ser = new JsonSerializer<Date>() {
  @Override
  public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext 
             context) {
    return src == null ? null : new JsonPrimitive(src.getTime());
  }
};

JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {
  @Override
  public Date deserialize(JsonElement json, Type typeOfT,
       JsonDeserializationContext context) throws JsonParseException {
    return json == null ? null : new Date(json.getAsLong());
  }
};

Gson gson = new GsonBuilder()
   .registerTypeAdapter(Date.class, ser)
   .registerTypeAdapter(Date.class, deser).create();

如果使用 Java 8 或更高版本,您应该像这样使用上述序列化器/反序列化器:

If using Java 8 or above you should use the above serializers/deserializers like so:

JsonSerializer<Date> ser = (src, typeOfSrc, context) -> src == null ? null
            : new JsonPrimitive(src.getTime());

JsonDeserializer<Date> deser = (jSon, typeOfT, context) -> jSon == null ? null : new Date(jSon.getAsLong());

这篇关于GSON - 日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆