将JSON REST Web服务中的日期序列化为ISO-8601字符串 [英] Serialize Date in a JSON REST web service as ISO-8601 string
问题描述
我有一个使用JBoss AS 7.1的JAX-RS应用程序,我发布/获取了包含日期(java.util.Date)的JSON和XML对象:
I have a JAX-RS application using JBoss AS 7.1, and I POST/GET JSON and XML objects which include Dates (java.util.Date):
@XmlRootElement
@XmlAccessorType(XmlAccessField.FIELD)
public class MyObject implements Serializable
{
@XmlSchemaType(name = "dateTime")
private Date date;
...
}
当我在get方法上使用@Produce("application/xml")时,objets被序列化为XML,并且日期被转换为ISO-8601字符串(例如"2012-12-10T14:50:12.123 + 02" :00).
When I use @Produce("application/xml") on the get method, the objets are serialized as XML and the dates are converted into ISO-8601 strings (e.g. "2012-12-10T14:50:12.123+02:00").
但是,如果我在get方法上使用@Produce("application/json"),则JSON对象中的日期是时间戳(例如"1355147452530"),而不是ISO-8601字符串.
However, if I use @Produce("application/json") on the get method, the dates in the JSON objects are timestamps (e.g. "1355147452530") instead of ISO-8601 strings.
如何配置JAX-RS实现(RESTEasy)以将JSON格式的日期序列化为ISO-8601字符串而不是时间戳?
How can I do to configure the JAX-RS implementation (RESTEasy) to serialize dates in JSON format as ISO-8601 strings instead of timestamps ?
谢谢您的回答.
注意:我还尝试使用自定义JAX-RS提供程序对日期进行JSON序列化
Note: I also tried to use a custom JAX-RS provider to do the JSON serialization for Dates
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class CustomJsonDateProvider implements MessageBodyWriter<Date>
{
...
}
此提供程序似乎是由RESTeasy在JBoss启动时注册的:
This provider seems to be registered by RESTeasy on JBoss startup:
[org.jboss.jaxrs] Adding JAX-RS provider classes: package.CustomJsonDateProvider
...
[org.jboss.resteasy.cdi.CdiInjectorFactory] No CDI beans found for class package.CustomJsonDateProvider. Using default ConstructorInjector.
但从未使用过!
推荐答案
我假设您的json解析器是Jackson,请尝试:
I assume your json parser is Jackson, try:
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET")
public Date date;
(自Jackson 2.0起)
(since Jackson 2.0)
这篇关于将JSON REST Web服务中的日期序列化为ISO-8601字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!