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);

	}
}

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s