Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

java - Spring 3.1 JSON date format

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

@Controller
@RequestMapping("/test")
public class MyController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class,
                  new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }


    @RequestMapping(value = "/getdate", method = RequestMethod.GET)
    public @ResponseBody Date getDate(@RequestParam("dt") Date dt, Model model) {
        // dt is properly constructed here..
        return new Date();
    }
}

When i pass in date, i am able to receive the date in the format. But my browser displays date as numeric

1327682374011

How do i make it display date in the format I have registered for the webbinder? I saw in some forum that I should use jackson mapper, but cant i alter the existing mapper?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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<Date> {    
    @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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...