问题

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

这就像Gson不关心对象"Date"并以其方式打印它。

我怎么能改变呢?

谢谢

编辑:

@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()不起作用:(


#1 热门回答(252 赞)

你似乎需要为日期和时间部分定义格式或使用基于字符串的格式。例如:

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

orusing java.text.DateFormat

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

或者使用序列化器来完成:

我相信格式化程序不能生成时间戳,但这个序列化器/解串器对似乎有效

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();

#2 热门回答(53 赞)

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();

以上格式对我来说似乎更好,因为它具有高达毫米的精度。

编辑格式引用'Z'


#3 热门回答(3 赞)

作为M.L.指出,JsonSerializer在这里工作。但是,如果要格式化数据库实体,请使用java.sql.Date注册序列化程序。不需要解串器。

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

此错误报告可能是相关的:http://code.google.com/p/google-gson/issues/detail?id=230。我使用1.7.2版本。


原文链接