My Quotes


When U were born , you cried and the world rejoiced
Live U'r life in such a way that when you go
THE WORLD SHOULD CRY






Saturday, March 8, 2014

TimeStamp Adapters for JAXB

As we have seen in many cases, the Timestamp coming in as Sting, it is easier to cast it using JAXB.

Here is the TimeStampAdapter which we can use it to streamline the same

Just define the TimeStamp attribute of the JAXB Object as date as follows
    @XmlElement(name = "ActionTimestamp")
    @XmlJavaTypeAdapter(TimeStampAdapter.class)
    private Date actionTimestamp;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class TimeStampAdapter extends XmlAdapter {
    private SimpleDateFormat firstFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    private SimpleDateFormat secondTimeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");

    @Override
    public String marshal(Date v) {
 return firstFormat.format(v);
    }

    @Override
    public Date unmarshal(String v) throws ParseException {
 Date returnDate = null;
 try {
     returnDate = firstFormat.parse(v);
 } catch (Exception prse) {
     returnDate = secondFormat.parse(v);
 }
 return returnDate;
    }
}

No comments :