Customizing the JSON output generated by Jackson

Recently i was using Jackson JSON Processor for converting java object into JSON. When i did that i noticed JackSon was storing date in the long format i.e. it was converting date.getTime() and using that long value in JSON instead of formatted date. This is how my Contact object looks like Note: please ignore line 32 @JsonSerialize(using = CustomDateSerializer.class) for now. I had following code to create object of Contact and converting and then using Jackson to convert it to String and write it on console This was the output that got generated

{"firstName":"Sachin","lastName":"Tendulkar","dateOfBirth":60065349443063}
Now i wanted to customize how the date so that it got generated in dd-MMM-yyyy format. In order to do that i started by creating CustomDateSerializer class like this Then i had to change the Contact.java class to add @JsonSerialize(using = CustomDateSerializer.class) annotation to getDateOfBirth() field, i could attach it to any other date field that i want. Now when i run JSONTester this the output that it generates

{"firstName":"Sachin","lastName":"Tendulkar","dateOfBirth":"24-Apr-1973"}
You can download the source code for this program from here

No comments: