Convert XML to JSON with Org.Json JSONObject
and XML
class.
XML Input
<?xml version="1.0" encoding="UTF-8"?> <student> <id>1</id> <name>Elen</name> <courses> <course> <courseId>1</courseId> <courseName>Java Programming</courseName> </course> <course> <courseId>2</courseId> <courseName>Python Programming</courseName> </course> </courses> </student>
JSON Output
{"student":{"name":"Elen","course":[{"courseName":"Java Programming","courseId":1},{"courseName":"Python Programming","courseId":2}],"id":1}}
Maven Dependency
<!-- https://mvnrepository.com/artifact/org.json/json --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20220320</version> </dependency>
XML to JSON with Org.Json
package com.fordevs; // json.org dependencies import org.json.JSONObject; import org.json.XML; public class XmlToJson { public static void main(String[] args) { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<student>\n" + " <id>1</id>\n" + " <name>Elen</name>\n" + " <courses>\n" + " <course>\n" + " <courseId>1</courseId>\n" + " <courseName>Java Programming</courseName>\n" + " </course>\n" + " <course>\n" + " <courseId>2</courseId>\n" + " <courseName>Python Programming</courseName>\n" + " </course>\n" + " </courses>\n" + "</student>"; JSONObject jsonObject = XML.toJSONObject(xml); System.out.println(jsonObject); } }
This code contains:
- require json.org import dependencies
- main method, and inside the main method …
- assign input XML
- convert XML to JSONObject using org.json
- print console output
Console Output
{"student":{"name":"Elen","course":[{"courseName":"Java Programming","courseId":1},{"courseName":"Python Programming","courseId":2}],"id":1}}
GitHub Repository
https://github.com/for-devs-com/xml-to-json-with-org-json
Try it with replit.com
Under Construction