How to Convert JSON to XML Using Java

Jan 14, 2024

1 min read

Published in

To convert JSON to XML in Java, you can use libraries like Jackson or Gson for JSON processing and JAXB for XML handling. Below is a basic example using Jackson and JAXB:

Add dependencies to your project (assuming Maven):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.13.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.0</version>
    </dependency>
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.3</version>
    </dependency>
</dependencies>

Java code to convert JSON to XML:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

public class JsonToXmlConverter {

    public static void main(String[] args) {
        String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        try {
            // Convert JSON to Jackson JsonNode
            ObjectMapper jsonMapper = new ObjectMapper();
            JsonNode jsonNode = jsonMapper.readTree(jsonString);

            // Convert Jackson JsonNode to XML using XmlMapper
            XmlMapper xmlMapper = new XmlMapper();
            String xmlString = xmlMapper.writeValueAsString(jsonNode);

            // Print the XML representation
            System.out.println("XML output:\n" + xmlString);

            // If needed, you can also marshal the XML string to a Java object
            // For example, if you have a class named Person:
            // Person person = xmlMapper.readValue(xmlString, Person.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Make sure to replace the jsonString variable with your actual JSON input. This example prints the XML representation of the JSON data using Jackson and XmlMapper.

Sharing is caring!