Convert JSON to XML in Java with Gson & JAXB – Step‑by‑Step Guide
What is JSON?
JSON (JavaScript Object Notation) is a lightweight, language‑agnostic data format that uses key‑value pairs. It’s widely adopted for data interchange and is easily stored in files or databases.
{
"username": "guru99user",
"email": "guru99user@mail.com"
}
Key characteristics:
- Enclosed in curly braces {}.
- Keys and string values are quoted.
- Pairs are separated by commas.
- Keys use letters, digits, underscore; no leading digits or spaces.
What is XML?
XML (eXtensible Markup Language) is a W3C standard for structured data. Unlike HTML, XML is purely a data format—no visual rendering. It allows custom tags, making it ideal for cross‑system data exchange.
Typical node structure:
<node>content</node>
At the top of an XML file you must declare the version:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
What is Gson?
Gson is a Java library that serialises Java objects to JSON and deserialises JSON back to Java objects. Since v1.6 it also supports streaming via JsonReader and JsonWriter.
Example of a streaming writer:
JsonWriter writer = new JsonWriter(new FileWriter(filePath));
writer.beginObject();
writer.name("key").value("value");
writer.endObject();
writer.close();
What is JAXB?
JAXB (Java Architecture for XML Binding) maps Java classes to XML using annotations. It supports marshalling (Java → XML) and unmarshalling (XML → Java).
Common annotations:
@XmlRootElement– defines the root XML element.@XmlElementWrapper– wraps collections.@XmlElement– maps a field to an XML element.@XmlAttribute– maps a field to an XML attribute.
Project Setup
- Create a Java project in your IDE (e.g., Eclipse).
- Name it XmlToJsonExample.
- Add a
data/inputfolder containingsample.xmlandsample.json. - Include Gson 2.8.5 in the build path.
- Add the JAXB API (usually bundled with Java 8).
Sample Data
XML representation of a department with roles and persons:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<department>
<roles>
<role id="1">
<position>head</position>
<salary>10k</salary>
</role>
<role id="2">
<position>manager</position>
<salary>8k</salary>
</role>
<role id="3">
<position>employee</position>
<salary>5k</salary>
</role>
</roles>
<persons>
<person id="1">
<name>Red</name>
<role>1</role>
</person>
<person id="2">
<name>Green</name>
<role>2</role>
</person>
<person id="3">
<name>Blue</name>
<role>2</role>
</person>
<person id="4">
<name>Yellow</name>
<role>3</role>
</person>
<person id="5">
<name>Brown</name>
<role>3</role>
</person>
</persons>
</department>
</root>
Equivalent JSON structure:
{
"roles": [
{"id":"1","position":"head","salary":"10k","persons":[{"id":"1","name":"Red"}]},
{"id":"2","position":"manager","salary":"8k","persons":[{"id":"2","name":"Green"},{"id":"3","name":"Blue"}]},
{"id":"3","position":"employee","salary":"5k","persons":[{"id":"4","name":"Yellow"},{"id":"5","name":"Brown"}]}
]
}
Java Model Classes
Define the following POJOs in the model package:
/* Role.java */
@XmlRootElement(name = "role")
public class Role {
private String id, position, salary;
// getters, setters with @XmlAttribute/@XmlElement annotations
}
/* Person.java */
@XmlRootElement(name = "person")
public class Person {
private String id, name, role;
// getters, setters with @XmlAttribute/@XmlElement annotations
}
/* Department.java */
@XmlRootElement(name = "department")
public class Department {
private List<Role> roles;
private List<Person> persons;
// getters/setters with @XmlElementWrapper/@XmlElement
}
/* XMLModel.java */
@XmlRootElement(name = "root")
public class XMLModel {
private Department department;
// getter/setter with @XmlElement
}
Unmarshalling XML to Java Objects (JAXB)
public XMLModel getObjectFromXmlFile(String path) throws JAXBException {
File file = new File(path);
JAXBContext ctx = JAXBContext.newInstance(XMLModel.class);
Unmarshaller um = ctx.createUnmarshaller();
return (XMLModel) um.unmarshal(file);
}
Marshalling Java Objects to XML (JAXB)
public void parseObjectToXml(String path, XMLModel model) throws JAXBException, IOException {
JAXBContext ctx = JAXBContext.newInstance(XMLModel.class);
Marshaller m = ctx.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(model, new FileOutputStream(path));
}
Serialising Java Objects to JSON (Gson)
public void writeDataToJsonFile(String path, List<Role> roles, List<Person> persons) throws IOException {
JsonWriter writer = new JsonWriter(new FileWriter(path));
writer.setIndent(" ");
writer.beginObject();
writer.name("roles").beginArray();
for (Role r : roles) {
writer.beginObject();
writer.name("id").value(r.getId());
writer.name("position").value(r.getPosition());
writer.name("salary").value(r.getSalary());
writer.name("persons").beginArray();
for (Person p : persons) if (p.getRole().equals(r.getId())) {
writer.beginObject();
writer.name("id").value(p.getId());
writer.name("name").value(p.getName());
writer.endObject();
}
writer.endArray();
writer.endObject();
}
writer.endArray();
writer.endObject();
writer.close();
}
Deserialising JSON to Java Objects (Gson)
public void getDataFromJsonFile(String path, List<Role> roles, List<Person> persons) throws IOException {
JsonReader reader = new JsonReader(new FileReader(path));
reader.beginObject();
while (reader.hasNext()) {
String rootName = reader.nextName();
if ("roles".equals(rootName)) {
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
Role r = new Role();
while (reader.hasNext()) {
String key = reader.nextName();
switch (key) {
case "id": r.setId(reader.nextString()); break;
case "position": r.setPosition(reader.nextString()); break;
case "salary": r.setSalary(reader.nextString()); break;
case "persons":
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
Person p = new Person();
p.setRole(r.getId());
while (reader.hasNext()) {
String pKey = reader.nextName();
if ("id".equals(pKey)) p.setId(reader.nextString());
else if ("name".equals(pKey)) p.setName(reader.nextString());
}
persons.add(p);
reader.endObject();
}
reader.endArray();
}
}
roles.add(r);
reader.endObject();
}
reader.endArray();
}
}
reader.endObject();
reader.close();
}
Full Conversion Workflow
- Unmarshal
sample.xmlintoXMLModelusing JAXB. - Serialize the resulting Java objects to
sample.jsonwith Gson. - Deserialize
sample.jsonback into Java objects. - Marshal those objects into a new XML file.
Conclusion
This guide demonstrates a clean, two‑step conversion pipeline: JAXB handles XML ↔ Java, while Gson handles JSON ↔ Java. By combining these libraries, developers can reliably transform data between formats in Java applications.
Java
- Encapsulation in Java: A Comprehensive Guide with Practical Example
- Java Variables and Data Types – A Comprehensive Guide with Examples
- Understanding Java Classes and Objects: Clear Concepts, Practical Examples
- Master Java String Manipulation: Essential Functions, Methods, and Practical Examples
- Understanding Java String.charAt(): Syntax, Return Type, Exceptions, and a Practical Example
- Mastering Java’s String.endsWith(): How to Check String Suffixes with Examples
- Java HashMap: A Comprehensive Guide
- Command‑Line Arguments in Java: A Practical Guide with Code Examples
- Java Abstraction: Mastering Abstract Classes, Methods, and Practical Examples
- Understanding Java's throws Keyword: Examples & Best Practices