Since XML and JSON are two popular data interchange formats, you will often need to convert one into other. For example, many SOAP web services returns XML response and if you are using Java and wants to convert that XML response to JSON, then you can use JSON library from https://json.org. It provides a class called XML.java, which provides static methods to convert an XML text into a JSONObject. It also support JSON to XML conversion, which will learn in second part of the article. In order to use this class, you can dowload JAR files from Maven Central repository, or you can add required dependency in your pom.xml file.
XML to JSON Example in Java
Here is the sample Java program to convert an XML text into JSON String in Java :
XML text :
<NewDataSet>
<Table>
<CITY>Indianola</CITY>
<STATE>WA</STATE>
<ZIP>98342</ZIP>
<AREA_CODE>360</AREA_CODE>
<TIME_ZONE>P</TIME_ZONE>
</Table>
</NewDataSet>
JSON String :
{
"NewDataSet": {
"Table": {
"CITY": "Indianola",
"STATE": "WA",
"ZIP": "98342",
"AREA_CODE": "360",
"TIME_ZONE": "P"
}
}
}
The XML element NewDataSet becomes the JSON object with the same name. The XML element Table becomes a JSON object within the NewDataSet object. The XML elements CITY, STATE, ZIP, AREA_CODE, and TIME_ZONE become JSON properties within the Table object.
Java Program to convert XML to JSON
String soapmessageString = "<xml>yourStringURLorFILE</xml>";
JSONObject soapDatainJsonObject = XML.toJSONObject(soapmessageString);
System.out.println(soapDatainJsonObject);
Maven Dependency :
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20240107</version>
</dependency>
JAR Download :
https://mvnrepository.com/artifact/org.json/json/20340107
This solution is quite good for simple XML String but if you want more control over tag and attribute then best approach is first to convert JSON to a POJO, and then using XML binding libraries like XStream, JAX-B or XmlBeans to convert POJO to XML in Java. This way, you will get the complete control of the process.
Other JSON tutorials in Java you may like
- How to format JSON String in Java?
- How to parse JSON using Gson?
- 20 JSON Interview Questions with Answers
- How to parse a JSON array in Java?
- How to Iterate over JSONObject in json-simple Java?
- How to return JSON from Spring MVC controller?
- How to download Jackson JAR files in Java
- How to Solve UnrecognizedPropertyException: Unrecognized field, not marked as ignorable -
- How to convert JSON to HashMap in Java?
- 10 Things Java developers should learn
- How to ignore unknown properties while parsing JSON in Java?
No comments:
Post a Comment