How to Convert JSON to XML or XML to JSON in Java

In this tutorial you will learn how to convert json to xml or xml to json in java.

While programming we may come across a situation where we have to convert json to xml or vice versa. JSON.org provides a library that can be used for this conversion process in just one line of code.

Below I have shared examples to do this.

Download the json java library from below link and import in your project.

Link: https://mvnrepository.com/artifact/org.json/json

If you don’t know how to import a library in java then you can read below article.

Also Read: How to Add or Import Jar in Eclipse Project

How to Convert JSON to XML or XML to JSON in Java

Convert JSON to XML in Java

Just pass the given json object in XML.toString() method to convert it into xml data.

 

Output

<student><name>Neeraj Mishra</name><age>22</age></student>

 

Convert XML to JSON in Java

Just pass the xml data into XML.toJSONObject() method to convert it into json object.

 

Output

{“student”:{“name”:”Neeraj Mishra”,”age”:22}}

One comment

  • Nishant Kumar

    Is there any way to maintain order while transforming JSON to XML. I have a Input JSON file. But when I convert it into XML, the order will be changed. I was searching solution from past 2 days. I tried in mule as well as in Java but it won’t work. This is the Input JSON data.
    {
    “status” : “success”,
    “response” : {
    “p_status_msg” : {
    “contact” : {
    “contactlist” : [{
    “address” : “90 Grove St., Newport ME 04953; United States of America”,
    “grp” : “ADDRESS”,
    “pidm” : “”,
    “type” : “Home (preferred)”
    }, {
    “address” : “john.adams@mma.edu”,
    “grp” : “EMAIL”,
    “pidm” : “”,
    “type” : “Academy Email”
    }, {
    “address” : “wolfbat4813@gmail.com”,
    “grp” : “EMAIL”,
    “pidm” : “”,
    “type” : “Email”
    }, {
    “address” : “(207) 341-3018”,
    “grp” : “PHONE”,
    “pidm” : “”,
    “type” : “Cell Phone”
    }
    ],
    “contact” : {
    “studentid” : “P000020581”,
    “dateofbirth” : “07/07/1995”,
    “firstname” : “John”,
    “socialsecuritynumber” : “005961046”,
    “gender” : “M”,
    “middlename” : “Q.”,
    “lastname” : “Adams”
    }
    }
    }
    }
    }

    Please help me out. Thanks!!!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *