GSON - 日期格式 [英] GSON - Date format
问题描述
我试图在Gson输出中使用自定义日期格式,但 .setDateFormat(DateFormat.FULL)
似乎不起作用,它与 .registerTypeAdapter(Date.class,new DateSerializer())
。
这就像Gson不关心对象日期并打印它的方式。
我该如何改变它?
谢谢
>编辑:
@Entity
公共类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()
不起作用:(
看来您需要为日期和时间部分定义格式,或者使用基于字符串的格式。 (),
$ b
Gson gson = new GsonBuilder()
.setDateFormat(EEE,dd MMM yyyy HH:mm:ss zzz ;
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<日期> deserialize(JsonElement json,Type typeOfT,
JsonDeserializationContext上下文)throws JsonParseException {
return json == null?()返回jsonDeserializer< Date>(){
@Override
public Date deserialize null:new Date(json.getAsLong());
}
};
gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class,ser)
.registerTypeAdapter(Date.class,deser).create();
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())
.
It's like Gson doesn't care about the object "Date" and print it in its way.
How can I change that?
Thanks
EDIT:
@Entity
public class AdviceSheet {
public Date lastModif;
[...]
}
public void method {
Gson gson = new GsonBuilder().setDateFormat(DateFormat.LONG).create();
System.out.println(gson.toJson(adviceSheet);
}
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();
Gson gson = new GsonBuilder()
.setDateFormat(DateFormat.FULL, DateFormat.FULL).create();
or do it with serializers:
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();
这篇关于GSON - 日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!