使用 Jakson 从 Spring 到网络的日期作为时间戳

Date from Spring to web as timestamp using Jakson

我有 Match class 和字段 Date start。我的目标是作为时间戳开始。我使用 Spring、AngularJs 和 jackson 作为 json 转换器。

Spring 控制器:

 @RequestMapping(value = "/web2/getMatch", method =RequestMethod.POST)
    public @ResponseBody Match  getPicksHistory() {
        PickDAO pd = new PickDAO();
        return pd.getMatch();  
    }

在 AgularJS 控制器上:

var res = $http.post(urlSer.url+"web2/getMatch");
    res.success(function(data, status, headers, config) {
        // now returns data.start = "Aug 8, 2015 7:00:00 PM"
        // My goal is get as timestamp
    });

我假设 'timestamp' 你指的是数字时间戳而不是文本表示。您可以使用自定义 ObjectMapper:

@Component
@Primary
public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
    }
}

我使用 jackson-databind:2.6.1 和 JsonSerializer

@Component
public class JsonDateSerializer extends JsonSerializer<Date>{

   @Override
   public void serialize(Date date, JsonGenerator gen,
        SerializerProvider serializers) throws IOException,
        JsonProcessingException {
    gen.writeNumber(date.getTime());
   }

}