Monday, October 15, 2012

Customize Spring JSON output

Spring uses Jackson JSON from http://jackson.codehaus.org/ to serialize an object for json output. To change the default strategy to serialize/format a field in a bean, you can easily create your own serializer. Following is an example to customize date format in json oupt

1. Creat serializer

public class CustomDateSerializer extends JsonSerializer {
 public static Log logger=LogFactory.getLog(CustomDateSerializer.class);
 
 @Override
 public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException {
  
  SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
                String formattedDate = formatter.format(value);

  gen.writeString(formattedDate);

 }
}

2. Annotate bean property to use the serializer


public class TransactionHistoryBean{
  private Date date;

  @JsonSerialize(using = CustomDateSerializer.class)
  public Date getDate() {
      return date;
  }
}

5 comments:

  1. A bewildering web journal I visit this blog, it's unfathomably heavenly. Oddly, in this present blog's substance made purpose of actuality and reasonable. The substance of data is informative
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  2. Hi! Nice blog. We are also offering you QuickBooks Customer Service Phone Number. If you need any help regarding QuickBooks issues, dial 1-855-756-1077 for instant help.

    ReplyDelete
  3. Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important.Project Center in Chennai


    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Corporate TRaining Spring Framework the

    authors explore the idea of using Java in Big Data platforms.

    Spring Training in Chennai


    The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

    ReplyDelete