Hi I am serializing java POJO object to xml using faster-xml(https://github.com/FasterXML/jackson-dataformat-xml/wiki ).When i do that i got xml but it doesn't have any version and encoding in xml file.This is the format i need
<?xml version="1.0" encoding="utf-8"?>
<SampleRequest>
...
</SampleRequest>
But I got Only this one
<SampleRequest>
...
</SampleRequest>
Is there any configuration need to be added in jackson fasterxml anotation.
Data format extension for Jackson (http://jackson.codehaus.org) to offer alternative support for serializing POJOs as XML and deserializing XML as pojos. Support implemented on top of Stax API (javax. xml.
Jackson is a library for handling JSON in Java systems and now has support for XML from version 2. DOM4J is a memory-efficient library for parsing XML, XPath, and XSLT (eXtensible Stylesheet Language).
Configuration of XML Mapper Object XmlMapper extends ObjectMapper . Therefore, you can use XML in the same way that you use ObjectMapper . For example, register the Java 8 modules to enable the feature of parameter names, Java 8 time, and Java 8 data types.
You can configure your XmlMapper
to write the XML header.
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure( ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true );
As an example:
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import java.io.IOException;
public class Xml {
public static void main(String[] args) throws IOException {
// Important: create XmlMapper; it will use proper factories, workarounds
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
xmlMapper.writeValue(System.out, new SampleRequest());
}
}
class SampleRequest{
public int x = 1;
public int y = 2;
}
This generates the output:
<?xml version="1.0" encoding="UTF-8"?>
<SampleRequest>
...
</SampleRequest>
In case you want to set the version to 1.1 instead of 1.0, use ToXmlGenerator.Feature.WRITE_XML_1_1
.
Notice that Faster-XML team recommends to use Woodstox library. In case you use it, some other configurations can be set. Among all of them there is one related to setting double quotes:
public static final String P_USE_DOUBLE_QUOTES_IN_XML_DECL="com.ctc.wstx.useDoubleQuotesInXmlDecl";
at WstxOutputProperties.java
For more details check out configuring Woodstox parser.
For those wondering how to change single quotes to double quotes:
String propName = com.ctc.wstx.api.WstxOutputProperties.P_USE_DOUBLE_QUOTES_IN_XML_DECL;
xmlMapper.getFactory()
.getXMLOutputFactory()
.setProperty(propName, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With