Java
XML
JSON
Data Conversion
Programming

Quickest way to convert XML to JSON in Java

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If you need a quick XML-to-JSON conversion in Java, the fastest route is usually a library that can parse XML into a generic tree and serialize that tree as JSON. That approach is easy to implement, but it is important to understand that XML and JSON do not map perfectly, so "quickest" is not always the same as "most accurate for every schema."

Fastest Setup with org.json

For a small utility or migration script, org.json.XML is one of the shortest solutions. Add the dependency:

xml
1<dependency>
2  <groupId>org.json</groupId>
3  <artifactId>json</artifactId>
4  <version>20240303</version>
5</dependency>

Then convert XML to JSON in a few lines:

java
1import org.json.JSONObject;
2import org.json.XML;
3
4public class XmlToJsonExample {
5    public static void main(String[] args) {
6        String xml =
7            "<user>" +
8            "<name>Ada</name>" +
9            "<age>31</age>" +
10            "<active>true</active>" +
11            "</user>";
12
13        JSONObject json = XML.toJSONObject(xml);
14        System.out.println(json.toString(2));
15    }
16}

That is about as short as it gets. It is a good choice when you need a readable JSON version of XML for debugging, lightweight tooling, or one-off transformation jobs.

Use Jackson When You Need More Control

If you are already using Jackson, converting through its tree model is often a better long-term choice. It gives you more control over configuration and output formatting.

xml
1<dependency>
2  <groupId>com.fasterxml.jackson.core</groupId>
3  <artifactId>jackson-databind</artifactId>
4  <version>2.17.2</version>
5</dependency>
6<dependency>
7  <groupId>com.fasterxml.jackson.dataformat</groupId>
8  <artifactId>jackson-dataformat-xml</artifactId>
9  <version>2.17.2</version>
10</dependency>
java
1import com.fasterxml.jackson.databind.JsonNode;
2import com.fasterxml.jackson.databind.ObjectMapper;
3import com.fasterxml.jackson.dataformat.xml.XmlMapper;
4
5public class JacksonXmlToJson {
6    public static void main(String[] args) throws Exception {
7        String xml =
8            "<user>" +
9            "<name>Ada</name>" +
10            "<age>31</age>" +
11            "<active>true</active>" +
12            "</user>";
13
14        XmlMapper xmlMapper = new XmlMapper();
15        JsonNode tree = xmlMapper.readTree(xml.getBytes());
16
17        ObjectMapper jsonMapper = new ObjectMapper();
18        String json = jsonMapper.writerWithDefaultPrettyPrinter()
19            .writeValueAsString(tree);
20
21        System.out.println(json);
22    }
23}

This approach is a little more verbose, but it fits better if your application already depends on Jackson or you want to tweak serialization later.

Understand What "Conversion" Really Means

XML supports attributes, repeated elements, namespaces, mixed content, and ordering rules that do not translate cleanly into plain JSON objects. Because of that, automatic converters make choices for you.

That matters when:

  • an XML element can appear once or many times
  • attributes must be preserved in a specific shape
  • text content and child elements appear together
  • the target JSON must match a fixed API contract

If you need stable output for an external interface, consider parsing the XML into domain objects and then serializing those objects as JSON. It takes more code, but you control the schema instead of letting a generic converter guess.

Common Pitfalls

The biggest mistake is assuming XML-to-JSON conversion is lossless. It is not. Two different XML documents may collapse into the same-looking JSON structure, and some XML features need custom handling.

Another common issue is using a generic converter for production API output. Quick conversion libraries are great for tooling and internal workflows, but they may not produce the exact field names, arrays, or nesting rules your consumers expect.

Large documents can also become a problem if you read the entire XML into memory as a string. For huge inputs, use a streaming parser and map the relevant parts explicitly instead of relying on a single in-memory conversion.

Finally, malformed XML is still malformed XML. Wrap conversion code in exception handling and validate the input if the source is untrusted.

Summary

  • The quickest XML-to-JSON path in Java is usually a library such as org.json.XML.
  • Jackson is slightly more verbose but fits better into many existing Java applications.
  • Automatic conversion is convenient, but XML and JSON do not map perfectly.
  • For strict API contracts, parse into domain objects instead of relying on generic conversion rules.
  • For very large XML files, prefer streaming approaches over whole-document conversion.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.