Java Convert XML to JSON using Eclipse IDE Tutorial


In this tutorial, we show you how to convert XML to JSON in Java using Eclipse IDE. Used org.json.XML class from json-20170516.jar

 Java Convert XML to JSON using Eclipse IDE

Video Tutorials

Project Structure

Create New Java Project

  • Launch Eclipse IDE.
  • Go to File-> New-> Others... Select Java Project then click Next.
  • Type ConvertXmlToJson in the "Project name" field.
  • Click Finish.

Adding org.json.* lib to an Eclipse Project Folder

  • Right click this project
  • Select Bulid Path -> Configure Build Path...
  • Under Libraries tab, click Add JARS... or Add External JARs... and give the json-20170516.jar jar file
  • Click Apply
  • Click OK

Create Xml2Json Class

Create a Xml2Json class under com.jackrutorial package and write the following code in it.

package com.jackrutorial;

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

public class Xml2Json {
 private static final int PRETTY_PRINT_INDENT_FACTOR = 4;

 public static void main(String[] args){
  String xmlString = "Test 125Test 226";
  JSONObject jsonObject = XML.toJSONObject(xmlString);
  String jsonPrettyPrintString = jsonObject.toString(PRETTY_PRINT_INDENT_FACTOR);

As shown above, we will convert User XML to JSON Object

  <name>Test 1</name>
  <name>Test 2</name>

Run the Program

  • Right click to the class select Run As -> Java Application.


 "users": {
  "user": [
   "name": "Test 1",
   "age": 25
   "name": "Test 2",
   "age": 26

Required Libraries 

Previous Post
Next Post

post written by: