import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

XML.toJSONObject(xml_text).toString()

org.json.XML

Answer from KonK on Stack Overflow
๐ŸŒ
SourceForge
json-lib.sourceforge.net โ€บ apidocs โ€บ net โ€บ sf โ€บ json โ€บ xml โ€บ XMLSerializer.html
XMLSerializer (Overview (json-lib jdk 1.3 API))
Returns wether this serializer will skip adding namespace declarations to elements or not. ... Returns wether this serializer will skip whitespace or not. ... Returns wether this serializer will trim leading and trealing whitespace from values or not. ... Returns true if types hints will have a 'json_' prefix or not. ... Returns true if JSON types will be included as attributes. ... Creates a JSON value from a XML string.
Discussions

java - Is there a way to directly convert XML to JSON with the namespaces removed without any intermediate XML to XML transformations? - Stack Overflow
Off-the-shelf programs to convert XML to JSON almost invariably produce something that isn't quite the JSON you want. That's because you know more about the semantics of the data than the general-purpose program does. More on stackoverflow.com
๐ŸŒ stackoverflow.com
October 3, 2018
Remove namespace when parsing to json
There was an error while loading. Please reload this page ยท XML.toJsonObject() currently just translates everything into Json. But when you have name spacing, you cannot remove these More on github.com
๐ŸŒ github.com
1
August 20, 2018
Quickest way to convert XML to JSON in Java - Stack Overflow
What are some good tools for quickly and easily converting XML to JSON in Java? More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Convert XML to JSON format - Stack Overflow
I have to convert docx file format (which is in openXML format) into JSON format. I need some guidelines to do it. Thanks in advance. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 3
1

You could try the XmlMapper from jackson (com.fasterxml.jackson.dataformat.xml.XmlMapper)

XmlMapper xmlMapper = new XmlMapper();
JsonNode jsonNode = xmlMapper.readTree(string.getBytes());
ObjectMapper objectMapper = new ObjectMapper();
String value = objectMapper.writeValueAsString(jsonNode);

edit: Dependencies I've used

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.0</version>
</dependency>
<dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.9.0</version>
</dependency>
2 of 3
1

This question is a bit old but I would like to share my answer about the same task that I did recently! The requirement is: Having this xml:

<ns2:testplan>
 <ns2:snapshot>
    <ns2:revision>294</ns2:revision>
 </ns2:snapshot>
 <ns2:webId>70</ns2:webId>
 <ns2:title>Demo test plan 06</ns2:title>
</ns2:testplan>

We would like to convert it to:

{
  "ns2:testplan": {
    "ns2:snapshot": {
      "ns2:revision": 294
    },
    "ns2:title": "Demo test plan 06",
    "ns2:webId": 70
  }
}

Note that with the accepted response the root tag <ns2:testplan> and the namespace prefix are not included in the JSON. To configure XmlMapper to keep the namespace and add the root tag, proceed like this:

var module = new SimpleModule().addDeserializer(JsonNode.class, new JsonNodeDeserializer() {
        @Override
        public JsonNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            return ctxt.getNodeFactory()
                    .objectNode()
                    .set("ns2:testplan", super.deserialize(p, ctxt)); // this config adds the root tag
        }
    });

XMLInputFactory xmlInputFactory = new WstxInputFactory();
xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); // this one keeps the namespace prefix
XmlMapper xmlMapper = new XmlMapper(new XmlFactory(xmlInputFactory, new WstxOutputFactory()));
xmlMapper.registerModule(module);

Then use the code of the accepted answer to convert the XML to JSON.

๐ŸŒ
GitHub
github.com โ€บ stleary โ€บ JSON-java โ€บ issues โ€บ 434
Remove namespace when parsing to json ยท Issue #434 ยท stleary/JSON-java
August 20, 2018 - Hi, XML.toJsonObject() currently just translates everything into Json. But when you have name spacing, you cannot remove these. EG. SOME_THING
Author ย  huehnerlady
๐ŸŒ
JSON Formatter
jsonformatter.org โ€บ xml-to-json
Best XML to JSON Converter Online
XML to JSON is very unique tool for convert JOSN to XML and allows to download, save, share and print XML to JSON data.. XML to JSON support URL linking for sharing json. i.e. https://jsonformatter.org/xml-to-json/?url=https://gist.githubusercontent.com/jimmibond/8b75d0afcf249601174f1f504664072a/raw/c28e51ac26861d39f900d88e3c9fe2490374dbd9/xmlsample ยท No. It's not required to save and share code. If XML data is saved without login, it will become public.
๐ŸŒ
FreeFormatter
freeformatter.com โ€บ xml-to-json-converter.html
Free Online XML to JSON Converter - FreeFormatter.com
This free online tool lets you convert an XML file into a JSON file with your choice of indentation
Find elsewhere
Top answer
1 of 9
13

You may take a look at the Json-lib Java library, that provides XML-to-JSON conversion.

String xml = "<hello><test>1.2</test><test2>123</test2></hello>";
XMLSerializer xmlSerializer = new XMLSerializer();  
JSON json = xmlSerializer.read( xml );  

If you need the root tag too, simply add an outer dummy tag:

String xml = "<hello><test>1.2</test><test2>123</test2></hello>";
XMLSerializer xmlSerializer = new XMLSerializer();  
JSON json = xmlSerializer.read("<x>" + xml + "</x>");  
2 of 9
10

There is no direct mapping between XML and JSON; XML carries with it type information (each element has a name) as well as namespacing. Therefore, unless each JSON object has type information embedded, the conversion is going to be lossy.

But that doesn't necessarily matter. What does matter is that the consumer of the JSON knows the data contract. For example, given this XML:

<books>
  <book author="Jimbo Jones" title="Bar Baz">
    <summary>Foo</summary>
  </book>
  <book title="Don't Care" author="Fake Person">
    <summary>Dummy Data</summary>
  </book>
</books>

You could convert it to this:

{
    "books": [
        { "author": "Jimbo Jones", "title": "Bar Baz", "summary": "Foo" },
        { "author": "Fake Person", "title": "Don't Care", "summary": "Dummy Data" },
    ]
}

And the consumer wouldn't need to know that each object in the books collection was a book object.

Edit:

If you have an XML Schema for the XML and are using .NET, you can generate classes from the schema using xsd.exe. Then, you could parse the source XML into objects of these classes, then use a DataContractJsonSerializer to serialize the classes as JSON.

If you don't have a schema, it will be hard getting around manually defining your JSON format yourself.

๐ŸŒ
XML.com
xml.com โ€บ pub โ€บ a โ€บ 2006 โ€บ 05 โ€บ 31 โ€บ converting-between-xml-and-json.html
Converting Between XML and JSON
Pattern 5 is applied to the second item of the outer list. The second inner list is converted using a combination of patterns 3 and 6. Here is the resulting JSON structure, which is reversible without losing any information.
๐ŸŒ
Code Beautify
codebeautify.org โ€บ xmltojson
XML to JSON Converter Online to convert XML to JSON String, URL and File
If you're looking for an easy way to convert XML to JSON, you've come to the right place. Our XML to JSON converter is free and easy to use, simply paste your XML code into the input and hit the "XML to JSON" button.
๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ convert-xml-to-json-java
Converting XML to JSON in Java: A Comprehensive Guide โ€” javaspring.net
Converting XML to JSON in Java is a common task in modern software development. In this blog post, we have explored the fundamental concepts behind this conversion, various usage methods using popular libraries like Jackson and JSON.org, common practices for handling namespaces and attributes, ...
๐ŸŒ
Utilities and Tools
utilities-online.info โ€บ xmltojson
XML to JSON & JSON to XML converter online
If you enter the code in the XML input box, the converted JSON file will be: The below rules will be applied while performing the XML conversion: The attributes of the code will be treated as regular JSON properties. The sequence of two or more similar elements will be translated to a JSON array. The namespaces in the code are omitted from the resulting property names.
๐ŸŒ
Stackify
stackify.com โ€บ java-xml-jackson
Solving the XML Problem with Jackson - Stackify
March 18, 2023 - Reading from a java.io.InputStream โ€“ e.g. for streaming over a network connection ... The Jackson XML module supports the full range of annotations that Jackson provides for annotating our POJOs. This means that we can have one single set of beans, with one set of annotations and, depending on the ObjectMapper instance, we select whether we get XML or JSON.
๐ŸŒ
Microsoft Learn
social.msdn.microsoft.com โ€บ Forums โ€บ azure โ€บ en-US โ€บ 0462dbeb-f46f-46d4-87bf-3d22ea75480d โ€บ convert-xml-to-json-without-the-namespace
Convert xml to json() without the namespace - MSDN - Microsoft
November 13, 2017 - They're just random properties you are free to ignore. So, the easiest way for you do work with this is convert the SOAP to JSON first, then JSONPath to the actual document content.
๐ŸŒ
javathinking
javathinking.com โ€บ blog โ€บ convert-xml-to-json-java
Converting XML to JSON in Java โ€” javathinking.com
A: In most cases, you can convert XML to JSON. However, some complex XML structures with deep nesting, namespaces, and special attributes may require additional handling to ensure a meaningful conversion. A: Jackson is a more feature-rich and widely used library, suitable for complex applications. JSON.simple is lightweight and easier to use for simple conversions.
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ archive โ€บ msdn-technet-forums โ€บ 0462dbeb-f46f-46d4-87bf-3d22ea75480d
Convert xml to json() without the namespace | Microsoft Learn
They're just random properties you are free to ignore. So, the easiest way for you do work with this is convert the SOAP to JSON first, then JSONPath to the actual document content.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 24473479 โ€บ how-i-can-convert-xml-to-json-without-special-libraries-java
How I can convert XML to JSON? without special libraries. >JAVA - Stack Overflow
June 13, 2017 - Consider an XML a tree data structure - You'll need to build that tree. Each node in an XML contains a hash of attributes, and an array of child nodes - So would your "node" object. Work recursively and parse the XML text into this tree.
๐ŸŒ
Aspose
products.aspose.com โ€บ aspose.cells โ€บ java โ€บ conversion โ€บ xml to json
Convert XML to JSON in Java
November 13, 2025 - Add a library reference (import the library) to your Java project. Load XML file with an instance of Workbook class. Convert XML to JSON by calling Workbook.save method.