Java objects serialization with JAXB.
Serialization makes possible to convert JAVA objects into Bytes for network submissions, but sometimes you need an intermediate file format such as XML, to ensure compatibility between different platforms.
In this tutorial we will learn how to serialize any JAVA object into XML with the JAXB APIs of ORACLE.
JAXB: allow to create Java classes from schemas and vice versa. It facilitates the use of XML in Java by compiling an XML schema in one or more classes
.
Prerequisites:
IDE : Eclipse, STS.
We will create a simple JAVA project with 3 packages, to separate the models (class to be processed), the conversion class, and the class to test (containing a main method).
We start by creating the class to serialize:
Adherent.java
notice that we used the @XmlRootElement annotation to allow the mapping between the class and the XML.
JAXBContext: the entry point to use the JAXB API.
MarShaller: this is the object that allows you to format the XML document.
StringWriter: is the object that allows you to create a stream from a JAVA object, never forget to use
close() at the end of the process.
you can notice that we use a factory that will save the file by concatenating the name of the class of the object to be serialized and the date / time of the processing plus the extension .xml (useful for the automation of treatment).
Finally, the class containing the main() method to test the application:
ExecSerialisation.java
notice that this application can serialize any class written in java.
you just have to run it as a Java application.
Here is the result :
Commentaires
Enregistrer un commentaire