Spring 3.1 JSON date format

后端 未结 3 1683
挽巷
挽巷 2020-11-30 00:45

I am using annotated Spring 3.1 MVC code (spring-mvc) and when i send date object through the @RequestBody the date is showing up as numeric. This is my controller

3条回答
  •  执笔经年
    2020-11-30 01:21

    In order to override the default date formatting strategy of Jakson following are the step to follow:

    1. Extend JsonSerializer to create a new class for handling date formatting
    2. Override serialize(Date date, JsonGenerator gen, SerializerProvider provider) function to format date in your desired format and write it back to generator instance (gen)
    3. Annotate your date getter object to use your extended json serializer using @JsonSerialize(using = CustomDateSerializer.class)

    Code:

    //CustomDateSerializer class
    public class CustomDateSerializer extends JsonSerializer {    
        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws 
            IOException, JsonProcessingException {      
    
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = formatter.format(value);
    
            gen.writeString(formattedDate);
    
        }
    }
    
    
    //date getter method
    @JsonSerialize(using = CustomDateSerializer.class)
    public Date getDate() {
        return date;
    }
    

    Source: http://blog.seyfi.net/2010/03/how-to-control-date-formatting-when.html

提交回复
热议问题