我试图在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()不工作:(
你可以指定格式Gson Gson = builder.setDateFormat("yyyy-MM-dd").create();在这个方法中,你可以使用其他格式代替yyyy-MM-dd
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
Gson gson = builder.setDateFormat("yyyy-MM-dd").create();
你可以指定格式Gson Gson = builder.setDateFormat("yyyy-MM-dd").create();在这个方法中,你可以使用其他格式代替yyyy-MM-dd
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
Gson gson = builder.setDateFormat("yyyy-MM-dd").create();