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

天涯浪子 提交于 2019-11-29 09:10:43

I assume your json parser is Jackson, try:

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

(since Jackson 2.0)

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

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

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

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

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

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

here

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

here

http://wiki.fasterxml.com/JacksonHowToCustomSerializers

here

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

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

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);
  }
}
Bertrand RODRIGUES

Declare the same Serializer used by Soap/XML:

@XmlElement(name = "prealert_date")
@XmlSchemaType(name = "dateTime")
@JsonSerialize(using = XMLGregorianCalendarSerializer.class)
protected XMLGregorianCalendar prealertDate;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!