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}}

Leave a Reply

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