Format Json String using JsonSerializer.


At times it is required to format the values while creating the json for eg Date, numeric value. The jackson json library provide a class JsonSerializer which helps in formatting the Object value.

For e.g
Convert the date return from DB in MM-dd-yyyy

class Person{

private String name;
private String city;
private Date DOB;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public Date getDOB() {
		return DOB;
	}
        @JsonSerialize(using = JsonDateSerializer.class)
	public void setDOB(Date dOB) {
		DOB = dOB;
	}
}

public class JsonDateSerializer extends JsonSerializer {
	public void serialize(Object value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException {

	SimpleDateFormat formatter =
           new SimpleDateFormat("MM-dd-yyyy");
	String formattedDate = formatter.format(value);

	gen.writeString(formattedDate);

	}
}