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

前端 未结 4 1900
星月不相逢
星月不相逢 2020-12-18 18:31

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(Xm         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-18 19:14

    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 {
    
      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);
      }
    }
    

提交回复
热议问题