Developer Documentation
Java
Updated September 19, 2026

Convert JSON to XML in Java

Convert JSON objects to XML while making the mapping rules explicit in Java.

JSON and XML have different data models, so there is no single universal conversion. Libraries make choices about roots, arrays, attributes, text nodes, nulls, and invalid XML element names; document those choices in APIs.

Quick Start#

The following example uses the standard Java API or a widely used package for this task.

Using Jackson XML#

Java
1// Dependencies: jackson-databind + jackson-dataformat-xml2ObjectMapper jsonMapper = new ObjectMapper();3XmlMapper xmlMapper = new XmlMapper();45JsonNode node = jsonMapper.readTree(inputJson);6Object value = jsonMapper.treeToValue(node, Object.class);7String xml = xmlMapper.writer()8    .withRootName("root")9    .writeValueAsString(value);1011System.out.println(xml);

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Pretty output#

Java
1String xml = xmlMapper.writerWithDefaultPrettyPrinter()2    .withRootName("root")3    .writeValueAsString(value);

Important Notes#

Jackson XML has its own conventions for collections and attributes. Use explicit data classes/annotations when the exact XML contract matters.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement JSON → XML in other languages: