Parse xml java jackson

How to Marshal and Unmarshal XML with Jackson

Learn to convert a Java object to XML or from XML document to Java object using Jackson library. Jackson is an excellent solution if we are looking to convert a Java object to XML without JAXB.

Just to re-iterate, marshalling is the process of transforming Java objects into XML documents. Unmarshalling is the process of reading XML documents into Java objects.

Include the latest version of jackson-dataformat-xml from Maven repo.

 com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.13.0 

After importing Jackson, we can start using its XmlMapper class for reading and writing XML.

XmlMapper xmlMapper = new XmlMapper(); //POJO -> XML String xml = xmlMapper.writeValueAsString(pojo); //XML -> POJO Class pojo = xmlMapper.readValue(xml);

XMLMapper is the most important class for handling XML documents with Jackson. It provides methods to read and write XML to the following sources and targets.

  • String
  • Byte[]
  • java.io.File
  • java.io.InputStream and java.io.OutputStream
  • java.io.Reader and java.io.Writer
//Write to String String xml = xmlMapper.writeValueAsString(pojo); //Write to file xmlMapper.writeValue(new File("data.xml"), pojo); //Read from String Pojo pojo = xmlMapper.readValue(xmlString, Pojo.class); //Read from File Pojo pojo = xmlMapper.readValue(new File("data.xml"), Pojo.class);

Using its enable() and disable() methods, we can trun on and off various behaviors specific to XML marshalling and unmarshalling such as:

  • Handling null and empty values.
  • Handling date and time values
  • Handling enum values
  • Handling elements ordering
  • Pretty printing, etc.
xmlMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); xmlMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); xmlMapper.disable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT); xmlMapper.disable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

3. Customing Conversion with Jackson Annotations

Let us take an example of Article class. We will first check the default XML generated for its instance, and then we will customize the XML by applying annotations to the Article class.

class Article < private Long id; private String title; private Listtags; //Constructors, getters, setters and toString method >

In the following examples, we use the same code for marshalling.

XmlMapper xmlMapper = new XmlMapper(); Article article = new Article(1L, "Test Title", List.of("Tag1", "Tag2")); String articleXml = xmlMapper.writeValueAsString(article); System.out.println(articleXml);

3.1. Default XML without Annotations

The default XML takes the XML tag names from class and member field names, including capitalization.

Use @JacksonXmlRootElement to customize the name of the root element.

@JacksonXmlRootElement(localName = "article") class Article

Check out the generated XML putout.

Use @JacksonXmlProperty(isAttribute = true) to mark a field as an XML attribute rather than an XML element.

@JacksonXmlRootElement(localName = "article") class Article

Check out the generated XML putout.

Use @JacksonXmlElementWrapper to on a List type to create the list wrapper element. The individual elements can be customized using the @JacksonXmlProperty .

@JacksonXmlRootElement(localName = "article") class Article < @JacksonXmlProperty(isAttribute = true) private Long id; private String title; @JacksonXmlElementWrapper(localName = "tags") @JacksonXmlProperty(localName = "tag") private Listtags; . >

Check out the generated XML putout.

4. Pretty Printing the XML Output

If we want to pretty print the XML output then we can turn on the SerializationFeature.INDENT_OUTPUT on XMLMapper.

XmlMapper xmlMapper = new XmlMapper(); xmlMapper.enable(SerializationFeature.INDENT_OUTPUT); Article article = new Article(1L, "Test Title", List.of("Tag1", "Tag2")); String articleXml = xmlMapper.writeValueAsString(article); System.out.println(articleXml);

It will print the following XML.

Читайте также:  Synchronized java для static

This Jackson tutorial taught us to serialize and deserialize the Java Object to XML document with simple and easy examples. We learned to customize and use the XmlMapper class for controlling the specific behavior during the conversion processes.

Источник

Jackson XML Parsing

Recently, I have a task to parse XML document and found this awesome library called Jackson. Although it is famous in handling JSON parsing, their XML parsing implementation is pretty good and clean too.

Maven Dependency

  com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.12.3  

Refer here for latest version.

Jackson XML basic

To use Jackson XML library, we need to initialize a XmlMapper object.

XmlMapper xmlMapper = new XmlMapper(); 

Jackson will require us to write a POJO class map with the incoming XML document that we’re going to parse.

Reading XML

MyPOJO myPojo = xmlMapper.readValue(xmlString, MyPOJO.class); 

Writing XML

ByteArrayOutputStream bs = new ByteArrayOutputStream(); xmlMapper.writeValue(bs, myPojo); String xmlString = bs.toString(); 

Use writerWithDefaultPrettyPrinter() method to enable pretty print for XML mapper.

xmlMapper.writerWithDefaultPrettyPrinter().writeValue(bs, myPojo); 

Mapping root element

To map a root element (e.g. student ) we can use the annotation @JacksonXmlRootElement on the root level object that use in serialization.

@Data //lombok @JacksonXmlRootElement(localName = "student") public class Student  private String name; > 

Mapping XML property

 id="id001" _isClassRep="true" _isActive="true" > Adam 012540701  
1 2 3 4 5 6 7 8 9 10 11 12 13 14
@Data //lombok @JacksonXmlRootElement(localName = "student") @JsonPropertyOrder("id", "_isClassRep", "_isActive", "name", "phone">) class Student  @JacksonXmlProperty(isAttribute = true, localName = "map") private String id; @JacksonXmlProperty(isAttribute = true, localName = "_isActive") private boolean isActive; @JacksonXmlProperty(isAttribute = true, localName = "_isClassRep") private boolean isClassRep; private String phone; private String name; > 
  • Use @JsonPropertyOrder to specify the ordering when deserialize to XML string, else jackson will follow the variable ordering in POJO class.
  • Specify isAttribute (default= false ) in @JacksonXmlProperty to control if the target property is XML attribute / element.
  • Specify localName in @JacksonXmlProperty to have custom the element/attribute name that different with variable in POJO class.

Mapping XML collection

When dealing with array value jackson will add an extra element which contain all the value.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
@Data //lombok @JacksonXmlRootElement(localName = "student") @JsonPropertyOrder("id", "_isClassRep", "_isActive", "name", "phone">) class Student  @JacksonXmlProperty(isAttribute = true, localName = "map") private String id; @JacksonXmlProperty(isAttribute = true, localName = "_isActive") private boolean isActive; @JacksonXmlProperty(isAttribute = true, localName = "_isClassRep") private boolean isClassRep; private String phone; private String name; @JacksonXmlProperty(localName = "subject") private ListString> subjects; > 
 map="id001" _isClassRep="false" _isActive="true"> Adam 015248  english history mathematics   

To rename the container element we can simply add @JacksonXmlElementWrapper(localName = "subjects") :

@JacksonXmlElementWrapper(localName = "subjects") @JacksonXmlProperty(localName = "subject") private ListString> subjects; 
 map="id001" _isClassRep="false" _isActive="true"> Adam 015248  english history mathematics   

To remove the container element we can simply add @JacksonXmlElementWrapper(useWrapping = false)

@JacksonXmlElementWrapper(useWrapping = false) @JacksonXmlProperty(localName = "subject") private ListString> subjects; 
 map="id001" _isClassRep="false" _isActive="true"> Adam 015248 english history mathematics  

Conclusion

Although XML is not really favor by modern development comparing to JSON. However, it’s readable pleasant structure is definitely a plus point when you have a complex nested data structure. With the help of the library (like Jackson) that made parsing XML relatively simple, I believe XML will no obsolete in the future.

Источник

Parse XML to Java Objects Using Jackson

Join the DZone community and get the full member experience.

Parsing the XML document to Java objects using Jackson library is quite simple.

The following is the XML that we are going to parse.

 John Doe 26  Peter Parker 30  

To parse the above XML, we will use Jackson library. We have also included Apache Commons library for converting bytes to String. The maven dependency is as follows.

 com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.9.6  org.apache.commons commons-lang3 3.4 

We need to create the model objects according to the XML. There will be two model objects.

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import java.util.Arrays; @JacksonXmlRootElement(localName = "employees") public final class Employees < @JacksonXmlElementWrapper(localName = "employee", useWrapping = false) private Employee[] employee; public Employees() < >public Employees(Employee[] employee) < this.employee = employee; >public Employee[] getEmployee() < return employee; >public void setEmployee(Employee[] employee) < this.employee = employee; >@Override public String toString() < return "Employees'; > >
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; public final class Employee < @JacksonXmlProperty(localName = "id", isAttribute = true) private String id; @JacksonXmlProperty(localName = "first_name") private String firstName; @JacksonXmlProperty(localName = "last_name") private String lastName; @JacksonXmlProperty(localName = "age") private int age; public Employee() < >public Employee(String id, String firstName, String lastName, int age) < this.id = id; this.firstName = firstName; this.lastName = lastName; this.age = age; >public String getId() < return id; >public void setId(String id) < this.id = id; >public String getFirstName() < return firstName; >public void setFirstName(String firstName) < this.firstName = firstName; >public String getLastName() < return lastName; >public void setLastName(String lastName) < this.lastName = lastName; >public int getAge() < return age; >public void setAge(int age) < this.age = age; >@Override public String toString() < return "Employee'; > >

There are few annotations that were added to the model objects which play a key role. They are JacksonXmlRootElement, JacksonXmlElementWrapper and JacksonXmlProperty.

The following is the code to parse the above XML document.

import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; public class Parser < public static void main(String[] args) throws IOException < ObjectMapper objectMapper = new XmlMapper(); // Reads from XML and converts to POJO Employees employees = objectMapper.readValue( StringUtils.toEncodedString(Files.readAllBytes(Paths.get("/tmp/employees.xml")), StandardCharsets.UTF_8), Employees.class); System.out.println(employees); // Reads from POJO and converts to XML objectMapper.writeValue(new File("/tmp/fieldsets.xml"), fieldSet); >> 

Opinions expressed by DZone contributors are their own.

Источник

Deserialization – How to convert XML to Java Objects using Jackson API

The previous tutorials have explained the conversion of Java Objects to XML using Jackson API. This tutorial explains parsing the XML document to Java objects using Jackson API.

To parse the XML, we will use the Jackson library. Use the latest Jackson library.

 com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.13.0  

Jackson allows us to read the contents of an XML file and deserialize the XML back into a Java object. In our example, we will read an XML document containing details about an Employee, and use Jackson to extract this data and use it to create Java objects containing the same information.

First, let us create an XML document matching our class to read from. Create deserialize.xml with the following contents:

 Vibha Singh 30 75000.0 Manager +919999988822 abc@test.com female married  

Deserialization – It is the reverse of serializing. In this process, we will read the Serialized byte stream from the file and convert it back into the Class instance representation. Here, we are converting a XML to an Employee class object.

Let us add a deserializeFromXML() function to deserialize the XML file above into a Java object:

@Test public void deserializeFromXML() < XmlMapper xmlMapper = new XmlMapper(); String userDir = System.getProperty("user.dir"); // Converting Employee XML to Employee class object try < Employee emp = xmlMapper.readValue(new File(userDir + "\\src\\test\\resources\\XMLExample.xml"), Employee.class); System.out.println("Deserialized data: "); System.out.println("First Name of employee : " + emp.getFirstName()); System.out.println("Last Name of employee : " + emp.getLastName()); System.out.println("Age of employee : " + emp.getAge()); System.out.println("Salary of employee : " + emp.getSalary()); System.out.println("Designation of employee : " + emp.getDesignation()); System.out.println("Contact Number of employee : " + emp.getContactNumber()); System.out.println("EmailId of employee : " + emp.getEmailId()); System.out.println("Marital Status of employee : " + emp.getMaritalStatus()); System.out.println("Gender of employee : " + emp.getGender()); >catch (StreamReadException e) < e.printStackTrace(); >catch (DatabindException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >> >

The output of the above program is shown below:

Manipulating Nested Elements in XML

Let us enhance our XML file to add nested elements and loops, and modify our code to deserialize the following updated structure.

  John Dave William  00-428507 +917823561231 +91 1212898920 +91 9997722123 +91 8023881245   30 75000.0 Manager abc@test.com female married  

There will be a slight change in the deserializeFromXML() method for the nested XML Structure.

@Test public void deserializeFromXML() < XmlMapper xmlMapper = new XmlMapper(); String userDir = System.getProperty("user.dir"); // Converting Employee XML to Employee class object try < Employees employee2 = xmlMapper .readValue(new File(userDir + "\\src\\test\\resources\\NestedXMLExample.xml"), Employees.class); System.out.println("Deserialized data: "); System.out.println("First Name of employee : " + employee2.getName().getFirtsname()); System.out.println("Middle Name of employee : " + employee2.getName().getMiddlename()); System.out.println("Last Name of employee : " + employee2.getName().getLastname()); System.out.println("Age of employee : " + employee2.getAge()); System.out.println("Salary of employee : " + employee2.getSalary()); System.out.println("Designation of employee : " + employee2.getDesignation()); System.out.println("Desk Number of employee : " + employee2.getContactdetails().getDeskNumber()); System.out.println("Mobile Number of employee : " + employee2.getContactdetails().getMobileNumber()); System.out.println("Emergency Number1 of employee : " + employee2.getContactdetails().getEmergencyDetails().getEmergency_no1()); System.out.println("Emergency Number2 of employee : " + employee2.getContactdetails().getEmergencyDetails().getEmergency_no2()); System.out.println("Emergency Number3 of employee : " + employee2.getContactdetails().getEmergencyDetails().getEmergency_no3()); System.out.println("EmailId of employee : " + employee2.getEmailId()); System.out.println("Gender of employee : " + employee2.getGender()); System.out.println("Marital Status of employee : " + employee2.getMaritalStatus()); >catch (StreamReadException e) < e.printStackTrace(); >catch (DatabindException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >> >

The output of the above program is shown below:

Here, you can see that when we need to serialize the nested attributes like Firstname, we have called the first Name class and then getFirstName().

System.out.println("First Name of employee : " + employee2.getName().getFirtsname());

To know about Serialization – Conversion of Java Objects to XML, you can refer to this tutorial – Serialization – How to convert Java Objects to XML using Jackson API.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Источник

Оцените статью