Java jackson xml to object

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.

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.

Источник

convert xml to Java object using jackson

I want to convert XML to JSON using Jackson library. I have tried below code to get Json as below using jackson but I can’t. if I tried using json, I can but I want to know how to do with Jackson library.

@RequestMapping(value="/convertXMLtoJson",method=RequestMethod.POST,consumes = MediaType.APPLICATION_XML_VALUE) public Map convertXMLtoJson(@RequestBody String strXMLData) < MapobjresponseMessage = null; ObjectMapper objObjectMapper = new ObjectMapper(); Employee objEmployee = null; try < JSONObject obj = XML.toJSONObject(strXMLData); ObjectMapper objectMapper = new XmlMapper(); objEmployee = objectMapper.readValue(strXMLData, Employee.class); objEmployeeService.save(objEmployee); >catch (Exception e) < e.printStackTrace(); >return objresponseMessage; > 

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.HashSet out of VALUE_STRING token at [Source: (StringReader); line: 5, column: 15] (through reference chain: com.example.springboot.bean.Employee[«Skills»])

 A Z 20 Java J2EE MSSQl JAVA 4 1 1.5 Java WebServices MSSQL J2EE India  2 2.5 Java J2EE MySQL Spring India   
import java.io.Serializable; import java.util.List; import java.util.Set; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; @Document @JacksonXmlRootElement(localName="EmployeeDetail") public class Employee implements Serializable < @Id private String userId; @JacksonXmlProperty(localName="FirstName") @JsonProperty("FirstName") private String firstName; @JacksonXmlProperty(localName="LastName") @JsonProperty("LastName") private String lastName; @JacksonXmlProperty(localName="Age") @JsonProperty("Age") private Integer age; @JacksonXmlElementWrapper(localName="Skills") @JsonProperty("Skills") private Setskills; @JacksonXmlProperty(localName="JobDetails") @JsonProperty("JobDetails") private List jobDetails; public String getUserId() < return userId; >public void setUserId(String userId) < this.userId = userId; >public Integer getAge() < return age; >public void setAge(Integer age) < this.age = age; >public String getLastName() < return lastName; >public void setLastName(String lastName) < this.lastName = lastName; >public String getFirstName() < return firstName; >public void setFirstName(String firstName) < this.firstName = firstName; >public List getJobDetails() < return jobDetails; >public void setJobDetails(List jobDetails) < this.jobDetails = jobDetails; >public Set getSkills() < return skills; >public void setSkills(Set skills) < this.skills = skills; >> import java.util.Set; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; @JacksonXmlRootElement(localName="JobDetails") public class JobDetails < JobDetails(String str) < >@JacksonXmlProperty(localName="CompanyName") @JsonProperty("CompanyName") private String companyName; @JacksonXmlProperty(localName="Experience") @JsonProperty("Experience") private Integer experience; @JacksonXmlProperty(localName="Location") @JsonProperty("Location") private String location; @JacksonXmlElementWrapper(localName="Technologies") @JsonProperty("Technologies") private Set technologies; public String getCompanyName() < return companyName; >public void setCompanyName(String companyName) < this.companyName = companyName; >public Integer getExperience() < return experience; >public void setExperience(Integer experience) < this.experience = experience; >public String getLocation() < return location; >public void setLocation(String location) < this.location = location; >public Set getTechnologies() < return technologies; >public void setTechnologies(Set technologies) < this.technologies = technologies; >> 

Источник

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