Of course! Converting XML to JSON in Java is a common task. There are several excellent libraries to achieve this, each with its own strengths. I'll cover the most popular and robust options.
Summary of Options
| Library | Pros | Cons | Best For |
|---|---|---|---|
| Jackson | Industry standard, highly flexible, excellent performance, full control over mapping. | Can be complex for simple, one-off conversions. | Production applications, complex XML schemas, performance-critical systems. |
| Gson | Simple API, good for straightforward conversions. | Less powerful than Jackson for complex XML/JSON mapping. | Simple projects, or if you're already using Gson for JSON. |
| Simple | Very easy to use, minimal boilerplate code. | Less flexible, can have issues with complex nested structures or attributes. | Quick prototypes and simple, predictable XML files. |
| JAXB | Built into Java (JDK 6+), standard for data binding. | Primarily for Java objects, not direct XML-to-JSON. Requires an intermediate POJO step. | When you're already working with JAXB for XML processing. |
Jackson (Recommended)
Jackson is the most popular and feature-rich library for JSON processing in Java. It has a dedicated module, jackson.dataformat.xml, for reading XML and seamlessly converting it to JSON.
Step 1: Add Dependency
Include the Jackson XML module in your project. If you're using Maven, add this to your pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.15.2</version> <!-- Use the latest version -->
</dependency>
For Gradle (build.gradle):
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.15.2' // Use the latest version
Step 2: Write the Java Code
Jackson provides an XmlMapper class, similar to the regular ObjectMapper, but for XML.
Example XML (data.xml):
<users>
<user>
<name>Alice</name>
<email>alice@example.com</email>
<age>30</age>
</user>
<user>
<name>Bob</name>
<email>bob@example.com</email>
<age>24</age>
</user>
</users>
Java Code:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.File;
import java.io.IOException;
public class JacksonXmlToJsonConverter {
public static void main(String[] args) {
// 1. Create an XmlMapper instance
XmlMapper xmlMapper = new XmlMapper();
try {
// 2. Read the XML file into a tree model (JsonNode)
// This is useful for inspecting the structure or modifying it before converting.
JsonNode rootNode = xmlMapper.readTree(new File("data.xml"));
// 3. Convert the JsonNode to a pretty-printed JSON string
ObjectMapper jsonMapper = new ObjectMapper();
String jsonString = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
// 4. Print the JSON
System.out.println(jsonString);
// --- Alternative: Directly to a Java Object ---
// If you have a corresponding Java class (e.g., Users.java), you can map directly.
// Users users = xmlMapper.readValue(new File("data.xml"), Users.class);
// String jsonStringFromObject = jsonMapper.writeValueAsString(users);
// System.out.println(jsonStringFromObject);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
{
"user" : [ {
"name" : "Alice",
"email" : "alice@example.com",
"age" : 30
}, {
"name" : "Bob",
"email" : "bob@example.com",
"age" : 24
} ]
}
Advanced Jackson: Handling Attributes and Lists
By default, Jackson handles attributes well, but for lists of elements, you might need to use @JacksonXmlProperty or @JacksonXmlElementWrapper for fine-grained control.
Example XML with attributes and a list:
<library>
<book id="101">
<title>Effective Java</title>
<author>Joshua Bloch</author>
</book>
<book id="102">
<title>Design Patterns</title>
<author>Erich Gamma</author>
</book>
</library>
Java Classes for Mapping:
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import java.util.List;
@JacksonXmlRootElement(localName = "library")
public class Library {
private List<Book> books;
// Getters and Setters
public List<Book> getBooks() { return books; }
public void setBooks(List<Book> books) { this.books = books; }
}
class Book {
@JacksonXmlProperty(isAttribute = true) // Treats 'id' as an attribute
private String id;
private String title;
private String author;
// Getters and Setters
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
}
Java Code to Convert:
// Use the same XmlMapper
XmlMapper xmlMapper = new XmlMapper();
Library library = xmlMapper.readValue(new File("library.xml"), Library.class);
ObjectMapper jsonMapper = new ObjectMapper();
String jsonString = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(library);
System.out.println(jsonString);
Output:
{
"books" : [ {
"id" : "101", : "Effective Java",
"author" : "Joshua Bloch"
}, {
"id" : "102", : "Design Patterns",
"author" : "Erich Gamma"
} ]
}
Gson (Alternative)
Gson is another excellent JSON library. While it doesn't have a native XML parser, you can combine it with a standard XML parser like javax.xml.parsers.DocumentBuilder.
Step 1: Add Dependency
<!-- For JSON processing -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version> <!-- Use the latest version -->
</dependency>
<!-- For XML parsing (usually part of JDK, but can be explicit) -->
<!-- No separate dependency needed for standard JDK parsers -->
Step 2: Write the Java Code
This approach is more manual as it involves converting the XML DOM tree to a JSON-serializable structure (like a Map).
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GsonXmlToJsonConverter {
public static void main(String[] args) {
try {
// 1. Parse XML file into a DOM Document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("data.xml"));
// 2. Convert Document to a Map
Map<String, Object> xmlMap = convertElementToMap(document.getDocumentElement());
// 3. Convert Map to JSON using Gson
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(xmlMap);
// 4. Print the JSON
System.out.println(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Map<String, Object> convertElementToMap(Element element) {
Map<String, Object> map = new HashMap<>();
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element childElement = (Element) node;
// If the element has children, recurse
if (childElement.hasChildNodes()) {
Object childValue = convertElementToMap(childElement);
// Handle lists of elements with the same name
if (map.containsKey(childElement.getTagName())) {
Object existingValue = map.get(childElement.getTagName());
List<Object> list;
if (existingValue instanceof List) {
list = (List<Object>) existingValue;
} else {
list = new ArrayList<>();
list.add(existingValue);
}
list.add(childValue);
map.put(childElement.getTagName(), list);
} else {
map.put(childElement.getTagName(), childValue);
}
} else {
// It's a simple element, just add its text content
map.put(childElement.getTagName(), childElement.getTextContent());
}
}
}
return map;
}
}
This Gson example is more complex because you have to manually handle the XML-to-Map conversion, which Jackson does for you automatically.
Simple (Quick and Easy)
The simple library lives up to its name by providing a very straightforward API.
Step 1: Add Dependency
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>4.6</version>
</dependency>
(Note: The simple library is often found within larger projects like JSQLParser, but the core simple functionality is what we need here).
Step 2: Write the Java Code
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import java.io.File;
// You need to define a Java class that matches the XML structure
class Users {
private User[] user;
// Getters and Setters are required by Simple
public User[] getUser() { return user; }
public void setUser(User[] user) { this.user = user; }
}
class User {
private String name;
private String email;
private int age;
// Getters and Setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
public class SimpleXmlToJsonConverter {
public static void main(String[] args) throws Exception {
// 1. Create a Serializer
Serializer serializer = new Persister();
// 2. Read the XML file into the Java object
Users users = serializer.read(Users.class, new File("data.xml"));
// 3. Use a standard JSON library (like Gson or Jackson) to convert the object to JSON
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(users);
// 4. Print the JSON
System.out.println(jsonString);
}
}
This approach requires you to define Java POJOs that mirror your XML structure, which can be a pro (type-safety) or a con (boilerplate code).
Recommendation
For most use cases, Jackson is the best choice. It's powerful, performant, and gives you fine-grained control over the conversion process without requiring you to write boilerplate mapping code for simple cases. The XmlMapper is specifically designed for this task and handles complex scenarios like lists and attributes gracefully.
