Tuesday, May 7, 2024
HomeJavaJAXB Date Format Instance utilizing Annotation

JAXB Date Format Instance utilizing Annotation


One of many frequent drawback whereas marshaling Java object to XML String utilizing JAXB is the default format of date and time offered by JAXB. When JAXB converts any Date sort object or XMLGregorianCalendar to XML String, exactly xsd:dateTime ingredient, it by default prints unformatted date e.g. 2012-05-17T09:20:00-04:30. Since a lot of the actual world, Java software has a requirement to print date in a specific format like dd-MM-yyyy or embody date and time in format dd-MM-yyyy HH:mm:ss, it turns into an issue. Fortunately, JAXB may be very extensible and gives hooks and adapters to customise marshaling and unmarshaling course of. You’ll be able to outline an extension of XmlAdapter to regulate and customise marshaling and unmarshaling or any Java sort relying upon yours want.

On this JAXB tutorial, we are going to see an instance of customizing JAXB to format date and time in an software particular format.

For our function, we are going to use the SimpleDateFormat class, which has its personal points, however that is okay for demonstration function. To get a readability of what’s the subject with the date format, and what we’re doing on this instance, contemplate following xml snippet, which is created from our Worker object, with out formatting Date, XML will appear to be:

<worker>
<identify>John</identify>
<dateofbirth>1985-01-15T18:30:00-04:00</dateofbirth>
<dateofjoining>2012-05-17T09:20:00-04:30</dateofjoining>
</worker>

Whereas after utilizing XmlAdapter for controlling marshaling of date object in JAXB, our XML String snippet will appear to be beneath:

XML String after formatting date in dd-MM-yyyy HH:mm:ss format

<worker>
 <identify>John</identify>
 <dateofbirth>15-01-1985 18:30:00</dateofbirth>
 <dateofjoining>17-05-2012 09:20:00</dateofjoining>
</worker>

You’ll be able to see that, within the second XML, dates are correctly formatted together with each date and time data. You’ll be able to even additional customise it into a number of different date codecs e.g. MM/dd/yyyy, you simply want to recollect SimpleDateFormat syntax for formatting dates, as proven right here.

JAXB Date Format Instance

Right here is the entire code instance of formatting dates in JAXB. It lets you specify Adapters, which can be utilized for marshaling and unmarshaling various kinds of object, for instance, you’ll be able to specify DateTimeAdapter for changing Date to String throughout marshaling, and XML String to Date throughout unmarshaling.

Aside from writing your personal Adapter, which ought to lengthen the XmlAdapter class, you additionally want to make use of annotation @XmlJavaTypeAdapter to specify that JAXB ought to use that adapter for marshaling and unmarshalling of a specific object.

On this JAXB tutorial, we now have written our personal DateTimeAdapter, which extends XmlAdapter and overrides marshal(Date object) and unmarshal(String xml) strategies. JAXB calls marshal technique, whereas changing Java Object to XML doc, and unmarshal technique to bind XML doc to Java object.

We’re additionally utilizing SimpleDateFormat class, to format Date object into dd-MM-yyyy HH:mm:ss format, which print date as 15-01-1985 18:30:00. By the way in which, watch out whereas utilizing SimpleDateFormat, as it is not thread-safe.

Java Program to transform Java Object to XML with formatted Dates

import java.io.StringWriter;
import java.textual content.DateFormat;
import java.textual content.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
 * JAXB tutorial to format Date to XML String whereas changing Java object to
 * XML paperwork i.e. throughout marshalling.
 *
 * @creator Javin Paul
 */
public class JAXBDateFormatTutorial {

    public static void predominant(String args[]) {
   
       Date dob = new GregorianCalendar(1985,Calendar.JANUARY, 15, 18, 30)
                        .getTime();
       Date doj = new GregorianCalendar(2012,Calendar.MAY, 17, 9, 20)
                        .getTime();  
       
       Worker john = new Worker("John", dob, doj);
 
       // Marshaling Worker object to XML utilizing JAXB
       JAXBContext ctx = null;
       StringWriter author = new StringWriter();
 
       attempt{
           ctx = JAXBContext.newInstance(Worker.class);
           ctx.createMarshaller().marshal(john, author);
           System.out.println("Worker object as XML");
           System.out.println(author);
     
       }catch(JAXBException ex){
           ex.printStackTrace();
       }
    }

}

When you’ll run this program it’ll print the Worker object in XML as proven beneath:

Worker object as XML
<?xml model="1.0" encoding="UTF-8" standalone="sure"?>
<worker>
<identify>John</identify>
<dateOfBirth>15-01-1985 18:30:00</dateOfBirth>
<dateOfJoining>17-05-2012 09:20:00</dateOfJoining>
</worker>

You’ll be able to see that dates are properly formatted and there’s no extra T in between because it was earlier than.

On this program, there are three predominant courses: Worker, DateTimeAdapter, and JAXBDateFormatTutorial, every class is coded of their respective file as a result of they’re public courses e.g. Worker.java accommodates Worker class. If you wish to embody then in the identical file, simply take away the public modifier from Worker and DateTimeAdapter class.

The Worker class is your area object whereas DateTimeAdapter is an extension of XmlAdapter to format dates whereas changing XML to Java object and vice-versa. 

Worker.java

@XmlRootElement(identify="worker")
@XmlAccessorType(XmlAccessType.FIELD)  
public class Worker{
    @XmlElement(identify="identify")
    personal String identify;

    @XmlElement(identify="dateOfBirth")
        @XmlJavaTypeAdapter(DateTimeAdapter.class)
    personal Date dateOfBirth;

    @XmlElement(identify="dateOfJoining")
    @XmlJavaTypeAdapter(DateTimeAdapter.class)
    personal Date dateOfJoining;

    // no-arg default constructor for JAXB
    public Worker(){}

    public Worker(String identify, Date dateOfBirth, Date dateOfJoining) {
        this.identify = identify;
        this.dateOfBirth = dateOfBirth;
        this.dateOfJoining = dateOfJoining;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public Date getDateOfJoining() {
        return dateOfJoining;
    }

    public void setDateOfJoining(Date dateOfJoining) {
        this.dateOfJoining = dateOfJoining;
    }

    public String getName() {
        return identify;
    }

    public void setName(String identify) {
        this.identify = identify;
    }

    @Override
    public String toString() {
        return "Worker{" + "identify=" + identify + ", dateOfBirth=" 
               + dateOfBirth + ", dateOfJoining=" + dateOfJoining + '}';

    }

}

DateTimeAdapter.java

public class DateTimeAdapter extends XmlAdapter<String, Date>{
    personal ultimate DateFormat dateFormat 
               = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

    @Override
    public Date unmarshal(String xml) throws Exception {
        return dateFormat.parse(xml);
    }

    @Override
    public String marshal(Date object) throws Exception {
        return dateFormat.format(object);
    }

}

Issues to Keep in mind

Listed below are a few essential issues to recollect whereas

1) Do not forget to supply a no argument default constructor to your area object e.g. Worker, failing to do will end result within the following error whereas marshaling Java Object to XML String:

com.solar.xml.inner.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions Worker doesn’t have a no-arg default constructor.
this drawback is expounded to the next location:

at Worker
at com.solar.xml.inner.bind.v2.runtime.IllegalAnnotationsException$Builder.test(IllegalAnnotationsException.java:91)
at com.solar.xml.inner.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:436)

at com.solar.xml.inner.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:277)

That is all on Learn how to format Dates in JAXB. We now have not solely realized Date formatting throughout marshaling of the Date object but additionally seen the right way to customise JAXB marshaling and unmarshalling course of. You should utilize this system to customise marshaling of any Java sort e.g. BigDecimal, float, or double, and many others. Simply keep in mind to make use of annotation @XmlJavaTypeAdapter to specify the identify of your customized date and time Adapter to the JAXB marshaller.

Different Java XML tutorials you could like

  • What’s the distinction between DOM and SAX parser in Java? (reply)
  • Step by Step information to parsing XML utilizing SAX parser in Java? (tutorial)
  • Prime 10 XML Interview Questions for Java Programmers? (FAQ)
  • Learn how to learn XML information utilizing DOM Parser in Java? (tutorial)
  • Learn how to escape XML Particular character in Java String? (tutorial)
  • Prime 10 XSLT Transformation Interview Questions? (FAQ)
  • Learn how to parse XML paperwork utilizing JDOM Parser in Java? (tutorial)
  • Learn how to create and consider XPath Expressions in Java? (information)

Thanks for studying this tutorial, in the event you like this tutorial then please share it with your folks and colleagues. In case you have any recommendations and suggestions then please share with us.


P. S. –
If you’re fascinated about studying the right way to take care of XML in Java in additional element, you’ll be able to learn Java and XML – Options of Actual World Drawback by Brett McLaughlin. It covers the whole lot with respect to parsing XML e.g. SAX, DOM, and StAX parser, JAXB, XPath, XSLT, and JAXB. One of many good books for superior Java builders. 



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments