我正在尝试在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()
不能工作:(
发布于 2011-07-29 23:17:08
似乎您需要定义日期和时间部分的格式,或者使用基于字符串的格式。例如:
Gson gson = new GsonBuilder()
.setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();
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();
如果使用Java 8或更高版本,您应该像这样使用上面的序列化程序/反序列化程序:
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());
发布于 2014-10-29 21:27:52
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();
上面的格式对我来说似乎更好,因为它的精度达到了millis。
发布于 2012-11-22 16:48:56
正如M.L.指出的那样,JsonSerializer在这里工作。但是,如果要格式化数据库实体,请使用java.sql.Date注册序列化程序。不需要反序列化程序。
Gson gson = new GsonBuilder()
.registerTypeAdapter(java.sql.Date.class, ser).create();
这个bug报告可能是相关的:http://code.google.com/p/google-gson/issues/detail?id=230。不过,我使用的是1.7.2版。
https://stackoverflow.com/questions/6873020
复制相似问题