Spring Jackson and Date Serialization problem

You make a nice restfull api using annotation driven controllers, and jackson mapping until
you discover that the date serialization gives you a timestamp.

This one


@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = "/mapdate.json",method = RequestMethod.GET)
    @ResponseBody
    public String getJsonDate() {

        Date date = new Date();

        Map map = new HashMap();
        map.put("date",date);

        try {
            return new ObjectMapper().writeValueAsString(map);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        throw new RuntimeException();
    }
}

Gives you this one

{"date":1358897343355}

😦

You can just get away with by changing the mapper configuration.

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = "/mapdate.json",method = RequestMethod.GET)
    @ResponseBody
    public String getJsonDate() {

        Date date = new Date();

        Map map = new HashMap();
        map.put("date",date);

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
            return new objectMapper.writeValueAsString(map);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        throw new RuntimeException();
    }
}

And the world is a better place

{"date":"2013-01-22T23:46:46.236+0000"}

This is a quick one, but since most of us want to have the date format of our choice you can extend the jsonserizalizer or instead of using a date just return a string from a formatted date with the usual DateFormat way.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.