Is there a way to convert a xml file to json? The XML can be of any structure, therefore there is no POJO class for instantiation. I need to convert the xml to json or to a Map, without root nodes.
For example:
<import name="person">
<item>
<firstName>Emil</firstName>
<lastName>Example</lastName>
<addresses>
<address>
<street>Example Blvd.</street>
</address>
<address>
<street>Example Ave.</street>
</address>
</addresses>
</item>
</import>
Expected JSON
{
"firstName": "Emil",
"lastName": "Example",
"addresses": [
{ "street" : "Example Blvd." },
{ "street" : "Example Ave." }
]
}
To convert an XML document to JSON, follow these steps: Select the XML to JSON action from the Tools > JSON Tools menu. Choose or enter the Input URL of the XML document. Choose the path of the Output file that will contain the resulting JSON document.
b - If you want to convert an XML content stored into a String, call the xml2json. fromStr('string with xml') method in your JavaScript script. It returns the JSON object. If you want to convert the XML to JSON String, add a second argument with the value of "string".
JSON is a lightweight data-interchange format based on a subset of the JavaScript language, and often offered as an alternative to XML in—for example—web services. To make life easier XSLTJSON allows you to transform XML to JSON automatically.
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
XML.toJSONObject(xml_text).toString()
org.json.XML
You can Use JSON and XML Library from json.org
import org.json.JSONObject;
import org.json.XML;
import org.junit.Test;
public class XmlToJsonTest {
private static final String XML_TEXT = "<note>\n" +
"<to>Tove</to>\n" +
"<from>Jani</from>\n" +
"<heading>Reminder</heading>\n" +
"<body>Don't forget me this weekend!</body>\n" +
"</note>";
private static final int PRETTY_PRINT_INDENT_FACTOR = 4;
@Test
public void convert() {
JSONObject xmlJSONObj = XML.toJSONObject(XML_TEXT);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
}
}
Source
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Output
{"note": {
"heading": "Reminder",
"from": "Jani",
"to": "Tove",
"body": "Don't forget me this weekend!"
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With