将 JSON REST Web 服务中的日期序列化为 ISO-8601 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13803391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:39:40  来源:igfitidea点击:

Serialize Date in a JSON REST web service as ISO-8601 string

jsonjax-rsjboss7.xresteasy

提问by Zlika

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):

我有一个使用 JBoss AS 7.1 的 JAX-RS 应用程序,我 POST/GET JSON 和 XML 对象,其中包括日期(java.util.Date):

@XmlRootElement
@XmlAccessorType(XmlAccessField.FIELD)
public class MyObject implements Serializable
{
    @XmlSchemaType(name = "dateTime")
    private Date date;
    ...
}

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/xml") 时,对象被序列化为 XML,日期被转换为 ISO-8601 字符串(例如“2012-12-10T14:50:12.123+02:00” )。

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.

但是,如果我在 get 方法上使用 @Produce("application/json"),则 JSON 对象中的日期是时间戳(例如“1355147452530”)而不是 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 实现 (RESTEasy) 以将 JSON 格式的日期序列化为 ISO-8601 字符串而不是时间戳?

Thank you for your answers.

谢谢您的回答。

Note: I also tried to use a custom JAX-RS provider to do the JSON serialization for Dates

注意:我还尝试使用自定义 JAX-RS 提供程序对日期进行 JSON 序列化

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class CustomJsonDateProvider implements MessageBodyWriter<Date>
{
    ...
}

This provider seems to be registered by RESTeasy on JBoss startup:

这个提供者似乎是在 JBoss 启动时由 RESTeasy 注册的:

[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.

but it is never used !

但它从未使用过!

回答by Dan

I assume your json parser is Hymanson, try:

我假设您的 json 解析器是 Hymanson,请尝试:

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET")
public Date date;

(since Hymanson 2.0)

(从Hyman逊 2.0 开始)

回答by Zlika

The default JBoss parser is Jettison, but I wasn't able to change the date format. So I switched to Hymanson and added the following class to my project to configure it:

默认的 JBoss 解析器是 Jettison,但我无法更改日期格式。所以我切换到 Hymanson 并在我的项目中添加了以下类来配置它:

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class HymansonConfig implements ContextResolver<ObjectMapper>
{
    private final ObjectMapper objectMapper;

    public HymansonConfig()
    {
        objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESPAMPS, false);
    }

    @Override
    public ObjectMapper getContext(Class<?> objectType)
    {
        return objectMapper;
    }
}

回答by Shivendra Prakash Shukla

Sorry people for yelling out loud - I found the answers here

对不起,人们大声喊叫 - 我在这里找到了答案

http://wiki.fasterxml.com/HymansonFAQDateHandling,

http://wiki.fasterxml.com/HymansonFAQDateHandling

here

这里

http://wiki.fasterxml.com/HymansonFAQ#Serializing_Dates,

http://wiki.fasterxml.com/HymansonFAQ#Serializing_Dates

here

这里

http://wiki.fasterxml.com/HymansonHowToCustomSerializers

http://wiki.fasterxml.com/HymansonHowToCustomSerializers

here

这里

http://Hymanson.codehaus.org/1.1.2/javadoc/org/codehaus/Hymanson/map/util/StdDateFormat.html

http://Hymanson.codehaus.org/1.1.2/javadoc/org/codehaus/Hymanson/map/util/StdDateFormat.html

Using the @JsonSerialize(using= ... ) way:

使用 @JsonSerialize(using= ... ) 方式:

public class JsonStdDateSerializer
extends JsonSerializer<Date> {

  private static final DateFormat iso8601Format =
    StdDateFormat.getBlueprintISO8601Format();

  @Override
  public void serialize(
    Date date, JsonGenerator jgen, SerializerProvider provider)
  throws IOException, JsonProcessingException {

    // clone because DateFormat is not thread-safe
    DateFormat myformat = (DateFormat) iso8601Format.clone();
    String formattedDate = myformat.format(date);
    jgen.writeString(formattedDate);
  }
}

回答by Bertrand RODRIGUES

Declare the same Serializerused by Soap/XML:

声明SerializerSoap/XML 使用的相同内容:

@XmlElement(name = "prealert_date")
@XmlSchemaType(name = "dateTime")
@JsonSerialize(using = XMLGregorianCalendarSerializer.class)
protected XMLGregorianCalendar prealertDate;