![](/img/trans.png)
[英]Always getting value of date field as current date after converting json into java object using JSONSerializer.toJava
[英]Java GSON JsonSerializer not convert Date type field of my model to Long value
我有这种方法
public String prepareResponseJson(Object result, ResultCode resultCode, String details) {
ResponseMessage responseMessage = new ResponseMessage<>(result, resultCode, details);
return gson.toJson(responseMessage);
}
和
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 = new GsonBuilder()
.registerTypeAdapter(Date.class, ser)
.registerTypeAdapter(Date.class, deser)
.registerTypeAdapter(XMLGregorianCalendar.class,
new Serializer()).registerTypeAdapter(XMLGregorianCalendar.class,
new Deserializer())
.serializeNulls().create();
当我尝试序列化此模型字段时
private java.util.Date lastModified;
我把这个放在Json字符串中
"lastModified": "окт 8, 2015",
但是模型有这个价值
lastModified - 2015-10-08
为什么日期转换错误? 在其他地方,我的转换器(日期串行器/解串器)工作正常。
您可以在创建GSON实例时指定数据格式:
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd").create();
您可以像这样将特定的日期格式添加到GsonBuilder中:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.