Convert XML to JSON with Jackson

How Jackson's XmlMapper turns XML into JSON, what it keeps and drops (root names, attributes, repeated elements, types), and when a typed mapping or plain XML is the better choice.

Jackson can read XML and write it back out as JSON with only a few lines of Java. The conversion is quick to set up, but it is a structural reinterpretation, not a faithful copy. XML can express things JSON has no direct slot for, such as attributes, namespaces, comments, mixed text and element order. This review explains what changes during the conversion, where meaning can be lost, and when the result is fit for use.

Short verdict: is Jackson's XML-to-JSON conversion suitable?

It suits data-oriented XML: configuration files, API payloads and records made of nested elements with simple text values. Its main benefit is that it reuses the Jackson stack many Java projects already depend on, so no separate XML library is needed. The decisive tradeoff is that the generic tree conversion guesses the JSON shape from each document. The same schema can therefore produce different JSON structures depending on how many child elements a document happens to contain.

Keep the original XML, or treat the JSON as a lossy view, in these cases: documents with mixed text and markup (such as prose or XHTML), signed XML, files that must validate against an XML schema, content that depends on namespaces or comments, and any workflow that must convert back to identical XML.

What the conversion actually changes

Despite the word "convert", nothing is reversed, mirrored or restyled. The characters inside text values pass through unchanged. What changes is the structure around them: elements, attributes and text nodes are mapped onto JSON objects, arrays and strings. Character and entity references such as & or é are decoded while the XML is parsed. In the JSON output they appear as ordinary characters, and the JSON writer adds escapes only where JSON syntax requires them.

The usual setup adds the jackson-dataformat-xml module, reads the XML into a JsonNode tree with XmlMapper, and writes that tree with a standard ObjectMapper:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

XmlMapper xmlMapper = new XmlMapper();
JsonNode tree = xmlMapper.readTree(xml);

ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writerWithDefaultPrettyPrinter()
        .writeValueAsString(tree);

The example below shows the documented default behavior of recent Jackson 2.x releases. It was not produced by a test run for this article, and output can differ between versions and configurations.

Input XML:
<order id="17">
  <item>pen</item>
  <item>ink</item>
  <price currency="USD">9.50</price>
</order>

Resulting JSON (tree conversion):
{
  "id" : "17",
  "item" : [ "pen", "ink" ],
  "price" : {
    "currency" : "USD",
    "" : "9.50"
  }
}

Several meaning-level changes are visible in that output:

  • The root element name (order) is gone. The tree holds only the root's contents.
  • Attributes and child elements become identical-looking fields. Nothing marks id as an attribute or item as an element.
  • Repeated sibling elements are merged into an array. Very old Jackson versions kept only the last value instead, so check the behavior of the version you use.
  • All values are strings. 17 and 9.50 stay "17" and "9.50" because XML text carries no type information.
  • An element that has both attributes and text stores the text under an empty-string key by default. The key name can be changed through the XML module configuration.
  • Namespace prefixes, comments and processing instructions are dropped.

The shape-instability problem

If the same order contained only one item element, the tree conversion would produce "item" : "pen", a string instead of an array. Code that consumes the JSON then has to handle both shapes. Empty elements are another weak spot: depending on the version and parser settings, an empty element can become an empty string or null. This variation is the main reason the generic tree approach suits inspection and prototyping better than stable data contracts.

For predictable output, map the XML onto Java classes instead. Use annotations such as JacksonXmlProperty (including its isAttribute option) and JacksonXmlElementWrapper, then serialize those objects to JSON. Each list is then always an array and each field keeps its declared type, regardless of how many elements a particular document contains. The cost is writing and maintaining the classes.

Approach | Best for | Main limitation
XmlMapper.readTree to JsonNode | Quick inspection, unknown or varied XML | JSON shape depends on each document; all values are strings
XmlMapper.readValue into annotated classes, then ObjectMapper | Stable APIs and data pipelines | Requires classes that match the XML structure
Keep XML, no conversion | Mixed content, signatures, schema validation, exact round trips | Consumers need XML tooling

Will the result stay readable and usable after copying or sharing?

The output is ordinary JSON text, so copying and pasting it does not change its meaning. Any JSON parser should read it the same way. It is not a visual effect or font substitution, so no special rendering support is needed. Text containing combining marks or emoji is carried through as the same code points. Jackson's writer can also be configured to escape non-ASCII characters as \u sequences if a destination only accepts ASCII; the meaning stays the same, but people find the result harder to read.

Three practical limits matter more than rendering. First, pretty-printed and compact JSON are equivalent, but the indented form is far easier to review and diff. Second, a screen reader or text search sees raw keys and punctuation, so for human readers a summary or table is usually better than shared JSON. Third, the conversion does not round-trip. Writing the JSON back to XML will not restore the root name, attribute-versus-element distinctions, namespaces or comments. Keep the source XML whenever exact reconstruction might be needed.

Evidence gaps

No version-specific test results, performance measurements or compatibility checks with particular downstream systems were available for this review. The behavior described comes from Jackson's documented defaults and is not a verified test. Before relying on the output, run representative documents through the exact Jackson version and configuration you plan to use. Include edge cases: single and repeated elements, empty elements, attributes alongside text, and namespaced content.