Spring MVC serializer calendar to json

Spring MVC serializer calendar to json

In this article, I’m using thymeleaf and data tables as my view, backend is Spring MVC Restful render list of data. The initial problem is my object attribute (calendar) display in timestamp format in view. To solved this problem u need to implement the custom jackson serializer.


Let’s create a class called JsonCalendarSerializer.java

package com.codeomitted.custom.serializer;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import org.springframework.stereotype.Component;

@Component
public class JsonCalendarSerializer extends JsonSerializer<Calendar> {

   private static final DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

   @Override
   public void serialize(
          Calendar calendar, JsonGenerator gen,
	  SerializerProvider arg2) throws IOException,
	  JsonProcessingException 
   {
          String strDate = formatter.format(calendar.getTime());
	  gen.writeString(strDate);
   }

}

Next, annotate @JsonAutoDetect in your Model class and annotate @JsonSerialize(using=JsonCalendarSerializer.class) on your attribute.

package com.codeomitted.model;
import java.util.Calendar;
import javax.persistence.Column;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import com.codeomitted.custom.serializer.JsonCalendarSerializer;
//.. import code omitted

@JsonAutoDetect
@Configurable
@Entity
@Table(name = "holidays")
public class Holidays {

    @Column(name = "Description", length = 50)
    private String description;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Id
    @Column(name = "Holiday_Dt")
    @DateTimeFormat(pattern="dd-MM-yyyy")
    @Temporal(TemporalType.TIMESTAMP)
    @JsonSerialize(using=JsonCalendarSerializer.class)
    private Calendar holidayDt;

    public Calendar getHolidayDt() {
        return this.holidayDt;
    }

    public void setHolidayDt(Calendar id) {
        this.holidayDt = id;
    }

}

 

POM, recently tested in version 1.8.x are not working, better use 1.9.2 or latest.

mvn clean eclipse:eclipse

<dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.9.13</version>			
</dependency>

In my html thymeleaf view and data tables.

//code omitted

<div class="dt-wrapper">
  <table style="width: 1138px;" aria-describedby="dt_colVis_Reorder_info" id="dataTable" class="table table-striped table-condensed dataTable">
	<thead>
	    <tr role="row">
		 <th width="20%">Holiday</th>
	         <th width="20%">Description</th>
	    </tr>
	</thead>
	<tbody> </tbody>
   </table>
</div>

// code omitted

<script type="text/javascript">
   // <![CDATA[

  $(document).ready(function() {

     $("#dataTable").dataTable({
        "bProcesing" : true,
	"bServerSide" : true,
	"bPaginate": true,
	"bLenthChange" : false,
	"iDisplayLength" : 20,
	"sAjaxSource" : "/codeomitteed/holidays/data",
	"aoColumns" : [
	    {
		 "sTitle" : "Holiday Date",
		 "mData" : "holidayDt"
	    },
	    {
	         "sTitle" : "Description",
		 "mData" : "description"
	    }
	 ],
	"sPaginationType" : "bootstrap",
	"sDom": "<'row-fluid'<'span6'><'span6'>r>t<'row-fluid'<'span6'i><'span6'p>>"

       });// dataTable
   });
   // ]]>
</script>

Controller code for response ajax called.

// code omitted

@RequestMapping(value = "/data", produces = "application/json")
public @ResponseBody String showData(
       @RequestParam(value = "iDisplayStart") Integer istart,
       @RequestParam(value = "iDisplayLength") Integer ilength, 
       @RequestParam(value = "sEcho") Integer sEcho,
       @RequestParam(value = "iSortCol_0") Integer sortCol,
       @RequestParam(value = "sSortDir_0") String  dirCol) 
   throws IOException
   {

   istart = (istart == null ? 0 : istart.intValue());
   ilength = (ilength == null ? 10 : ilength.intValue());

   long nrOfPages = service.countAllHolidays() / ilength;
   List<Holidays> list = service.findAndSortBy(start, ilength, sortCol.intValue(), dirCol);

   JsonData<Holidays> json = new JsonData<Holidays>();
   json.setAaData(list);// data
   json.setiTotalDisplayRecords(service.countAllHolidays());
   json.setiTotalRecords(nrOfPages);
   json.setsEcho(sEcho);

   ObjectMapper mapper = new ObjectMapper();
   try {
      return mapper.writeValueAsString(json);
   } catch (JsonProcessingException e) {
      e.printStackTrace();
      return null;
   }
}

In case u need to known JsonData is just a normal class to hold the value for serialise purpose.

public class JsonData<T> implements Serializable {

 	 private static final long serialVersionUID = 1L;
	 private List<T> aaData;
	 private int sEcho;
	 private long iTotalRecords;
	 private long iTotalDisplayRecords;

	 public DataTablesRequest() {

	 }

         //  getter setter code omitted

}

Backend code are using spring data. Partial code are show.

//code omitted

@Service
@Transactional
public class HolidayServiceImpl implements HolidaysService {

    @Autowired
    HolidaysDAO dao;

    // some other code omitted

    @Override
    public List<Holidays> findAndSortBy(
                        int firstResult,
			int maxResults, 
                        int sort, String dir) 
    {
	  return dao.findAll(new org.springframework.data.domain.PageRequest(firstResult / maxResults, maxResults, sortBy(sort,dir) )).getContent();
    }

    private Sort sortBy(int sort, String dir) {
	 String[] values = {"holidayDt", "description"};
	 return new Sort(dir.equalsIgnoreCase("asc")? Sort.Direction.ASC: Sort.Direction.DESC, values[sort]);
   }

   // code omitted

Done,

Write a Reply or Comment

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