How to Convert XML to JSON in Java

Converting XML to JSON in Java

In this post, We will show you simple program about, How to Convert XML to JSON in Java. The example program has been tested and shared in the same post.

Maven Dependency


Example Program

package com.dineshkrish;

import java.nio.file.Files;

import org.json.JSONObject;
import org.json.XML;

 * @author Dinesh Krishnan

public class Converter {
	// Converting XML to JSON
	public static JSONObject convert(String xml) {
		if(xml == null || xml.isEmpty()) {
			return null;
		return XML.toJSONObject(xml);

	public static void main(String[] args) {
		final String fileName = "input.xml";
		File xmlFile = new File(fileName);
		try {
			byte[] b = Files.readAllBytes(xmlFile.toPath());
			String xml = new String(b);
			JSONObject obj = convert(xml);
		} catch (IOException e) {

Sample Input

<?xml version="1.0" encoding="UTF-8"?>

	<empEmail>[email protected]</empEmail>
	<empPhone>+91 9941937705</empPhone>


  "employee": {
    "empId": 101,
    "empPhone": "+91 9941937705",
    "Address": {
      "country": "India",
      "city": "Chennai",
      "doorNo": 10,
      "state": "Tamilnadu"
    "empName": "John",
    "empEmail": "[email protected]",
    "empAge": 10


1. Quickest way to convert XML to JSON in Java – Stack Overflow
2. Convert JSON to Object
3. JSON and JSON Structure
4. XML and XML Structure