Jaxb Appointment Format Example Using Notation | Coffee Appointment To Xml Datetime String Conversion

One of the mutual work field marshaling Java object to XML String using JAXB is the default format of appointment in addition to fourth dimension provided past times JAXB. When JAXB converts whatever Date type object or XMLGregorianCalendar to XML String, exactly xsd:dateTime element, it past times default prints unformatted appointment e.g. 2012-05-17T09:20:00-04:30. Since most of the existent world, Java application has a requirement to impress appointment inward a especial format similar dd-MM-yyyy or include appointment in addition to fourth dimension inward format dd-MM-yyyy HH:mm:ss, it becomes a problem. Thankfully, JAXB is real extensible in addition to provides hooks in addition to adapters to customize marshaling in addition to unmarshaling process. You tin define an extension of XmlAdapter to command in addition to customize marshaling in addition to unmarshaling or whatever Java type depending upon yours need.

In this JAXB tutorial, nosotros volition come across an instance of customizing JAXB to format appointment in addition to fourth dimension inward an application specific format.

For our purpose, nosotros volition usage the SimpleDateFormat class, which has its ain issues, but that's ok for demonstration purpose. To acquire a clarity of what is the number amongst the appointment format, in addition to what nosotros are doing inward this example, consider next xml snippet, which is created from our Employee object, without formatting Date, XML volition hold back like:

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


While later using XmlAdapter for controlling marshaling of appointment object inward JAXB, our XML String snippet volition hold back similar below:

XML String later formatting appointment inward dd-MM-yyyy HH:mm:ss format

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

You tin come across that, inward the 2d XML, dates are properly formatted including both appointment in addition to fourth dimension information. You tin fifty-fifty farther customize it into several other appointment formats e.g. MM/dd/yyyy, y'all only bespeak to recall SimpleDateFormat syntax for formatting dates, every bit shown here.



JAXB Date Format Example

Here is the consummate code instance of formatting dates inward JAXB. It allows y'all to specify Adapters, which tin live on used for marshaling in addition to unmarshaling dissimilar types of object, for example, y'all tin specify DateTimeAdapter for converting Date to String during marshaling, in addition to XML String to Date during unmarshaling.

Apart from writing your ain Adapter, which should extend the XmlAdapter class, y'all besides bespeak to usage notation @XmlJavaTypeAdapter to specify that JAXB should usage that adapter for marshaling in addition to unmarshalling of a especial object.

In this JAXB tutorial, nosotros bring written our ain DateTimeAdapter, which extends XmlAdapter in addition to overrides marshal(Date object) in addition to unmarshal(String xml) methods. JAXB calls marshal method, field converting Java Object to XML document, in addition to unmarshal method to bind XML document to Java object.

We are besides using SimpleDateFormat class, to format Date object into dd-MM-yyyy HH:mm:ss format, which impress appointment every bit 15-01-1985 18:30:00. By the way, live on careful field using SimpleDateFormat, every bit it's non thread-safe.




Java Program to convert Java Object to XML amongst formatted Dates

import java.io.StringWriter; import java.text.DateFormat; import java.text.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 field converting Java object to  * XML documents i.e. during marshalling.  *  * @author Javin Paul  */ public class JAXBDateFormatTutorial {      public static void main(String args[]) {            Date dob = new GregorianCalendar(1985,Calendar.JANUARY, 15, 18, 30).getTime();        Date doj = new GregorianCalendar(2012,Calendar.MAY, 17, 9, 20).getTime();                  Employee privy = new Employee("John", dob, doj);          // Marshaling Employee object to XML using JAXB        JAXBContext ctx = null;        StringWriter author = new StringWriter();          try{            ctx = JAXBContext.newInstance(Employee.class);            ctx.createMarshaller().marshal(john, writer);            System.out.println("Employee object every bit XML");            System.out.println(writer);              }catch(JAXBException ex){            ex.printStackTrace();        }     }  }

When y'all volition run this programme it volition impress the Employee object inward XML every bit shown below:

Employee object every bit XML <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <employee> <name>John</name> <dateOfBirth>15-01-1985 18:30:00</dateOfBirth> <dateOfJoining>17-05-2012 09:20:00</dateOfJoining> </employee>

You tin come across that dates are nicely formatted in addition to at that topographic point is no to a greater extent than T inward betwixt every bit it was before.

In this program, at that topographic point are 3 primary classes: Employee, DateTimeAdapter, in addition to JAXBDateFormatTutorial, each shape is coded inward their respective file because they are populace classes e.g. Employee.java contains Employee class. If y'all desire to include in addition to thus inward the same file, only take away the public modifier from Employee in addition to DateTimeAdapter class.

The Employee shape is your domain object field DateTimeAdapter is an extension of XmlAdapter to format dates field converting XML to Java object in addition to vice-versa. As I said, JAXB is real extensible in addition to provides a lot of hooks where y'all tin insert your ain code for customization. If y'all desire to larn to a greater extent than close advanced usage of JAXB, I advise y'all reading Core Java Volume II - Advanced Features past times Cay S. Horstmann, i of the best books to larn XML parsing inward Java.

 One of the mutual work field marshaling Java object to XML String using JAXB is the de JAXB Date Format Example using Annotation | Java Date to XML DateTime String Conversion



Employee.java

@XmlRootElement(name="employee") @XmlAccessorType(XmlAccessType.FIELD)   public class Employee{     @XmlElement(name="name")     private String name;      @XmlElement(name="dateOfBirth")         @XmlJavaTypeAdapter(DateTimeAdapter.class)     private Date dateOfBirth;      @XmlElement(name="dateOfJoining")     @XmlJavaTypeAdapter(DateTimeAdapter.class)     private Date dateOfJoining;      // no-arg default constructor for JAXB     public Employee(){}      public Employee(String name, Date dateOfBirth, Date dateOfJoining) {         this.name = name;         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 name;     }      public void setName(String name) {         this.name = name;     }      @Override     public String toString() {         return "Employee{" + "name=" + cite + ", dateOfBirth="                 + dateOfBirth + ", dateOfJoining=" + dateOfJoining + '}';      }  }

DateTimeAdapter.java

public class DateTimeAdapter extends XmlAdapter<String, Date>{     private final 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);     }  }


 One of the mutual work field marshaling Java object to XML String using JAXB is the de JAXB Date Format Example using Annotation | Java Date to XML DateTime String Conversion


Things to Remember

Here are a distich of of import things to recall while

1) Don't forget to supply a no declaration default constructor for your domain object e.g. Employee, failing to exercise volition result inward the next fault field marshaling Java Object to XML String:

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions Employee does non bring a no-arg default constructor.
this work is related to the next location:

at Employee
at com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:91)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:436)

at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:277)

That's all on How to format Dates inward JAXB. We bring non only learned Date formatting during marshaling of the Date object but besides seen how to customize JAXB marshaling in addition to unmarshalling process. You tin usage this technique to customize marshaling of whatever Java type e.g. BigDecimal, float, or double etc. Just recall to usage notation @XmlJavaTypeAdapter to specify the cite of your custom appointment in addition to fourth dimension Adapter to JAXB marshaller.

Further Learning
Java In-Depth: Become a Complete Java Engineer!
Master Java Web Services in addition to REST API amongst Spring Boot
answer)
  • Step past times Step direct to parsing XML using SAX parser inward Java? (tutorial)
  • Top 10 XML Interview Questions for Java Programmers? (FAQ)
  • How to read XML file using DOM Parser inward Java? (tutorial)
  • How to escape XML Special grapheme inward Java String? (tutorial)
  • Top 10 XSLT Transformation Interview Questions? (FAQ)
  • How to parse XML document using JDOM Parser inward Java? (tutorial)
  • How to exercise in addition to evaluate XPath Expressions inward Java? (guide)

  • Thanks for reading this tutorial, if y'all similar this tutorial in addition to thus delight portion amongst your friends in addition to colleagues. If y'all bring whatever proffer in addition to feedback in addition to thus delight portion amongst us.

    P.S. - If y'all are interested inward learning how to bargain amongst XML inward Java inward to a greater extent than details, y'all tin read Java in addition to XML - Solutions of Real World Problem past times Brett McLaughlin. It covers everything amongst observe to parsing XML e.g. SAX, DOM, in addition to StAX parser, JAXB, XPath, XSLT, in addition to JAXB. One of the skilful mass for advanced Java developers. 

    Sumber https://javarevisited.blogspot.com/

    0 Response to "Jaxb Appointment Format Example Using Notation | Coffee Appointment To Xml Datetime String Conversion"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel