日期的JSON序列化策略 [英] JSON serialization strategy for dates
问题描述
我遇到的问题是,我有一些使用Java的使用者和一些使用浏览器的使用者.我的目标浏览器是IE7 +(仅适用于IE7的json3)和& Chrome.
The problem I am having is that I have some consumers that are Java and some that are browsers. My target browsers are IE7+ (json3 for IE7 only) & Chrome.
对于浏览器,我希望将日期反序列化为Date
JavaScript对象(使用JSON.parse()
方法.对于Java使用者,我希望反序列化为java.util.Date
Java对象.
For a browser I wish to have the date deserialize to a Date
JavaScript object (using the JSON.parse()
method. For a Java consumer I wish to deserialize to a java.util.Date
Java object.
鉴于我无法在浏览器端进行任何更改.我必须将消息序列化为这样的内容:
Given that I can't change anything on the browser side. I have to do serialize the messages to something like this:
{ myDate: new Date(<EPOCH HERE>) }
这当然会导致Java解串器出现问题.但是,我希望我可以使用Gson
做一些事情来使这项工作...有很多想法吗?
Which of course will cause a problem for Java deserializer. However, I am hoping there is something I can do with Gson
to make this work...amy ideas?
还是应该完全采用其他策略?
Or should I take a different strategy altogether?
推荐答案
我通常使用注释@JsonSerialize
和@JsonDeserialize
来解决此问题.我还使用ISO8601格式作为REST API日期的标准.
I usually use the annotation @JsonSerialize
and @JsonDeserialize
to deal with this problem. I also use ISO8601 format as a standard for our REST API dates.
@JsonSerialize(using=JsonDateSerializer.class)
@JsonDeserialize(using=JsonDateDeserializer.class)
private Date expiryDate;
JsonDateSerializer 类
@Component
public class JsonDateSerializer extends JsonSerializer<Date>
{
// ISO 8601
private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException
{
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}
JsonDateDeserializer 类
@Component
public class JsonDateDeserializer extends JsonDeserializer<Date>
{
// ISO 8601
private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException
{
try
{
return dateFormat.parse(jsonParser.getText());
}
catch (ParseException e)
{
throw new JsonParseException("Could not parse date", jsonParser.getCurrentLocation(), e);
}
}
}
这篇关于日期的JSON序列化策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!