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.
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
Top answer
1 of 1
2

The source XML file or string can be parsed in many different ways. I choose the XmlDocument class since it's simple to use and directly compatible with the JSON serializer.

The XML has two elements:
- A prolog that defines the XML version (but not the encoding: UTF-8 is assumed)
- A Root element (ATT_ADDR_VAL_RESP), which contains Attributes that need to be removed when the XML is converted to a JSON format.

The XmlDocument.Load() or XmlDocument.LoadXml() methods can be used to generate XML Document object.
- The former expects a Stream or a string that represents a Path to a file (or a Xml/Text Reader)
- The latter only parses XML strings

Assuming it's a Stream, we can generate the XmlDocument using its Load() method:

Dim doc = New XmlDocument()
doc.Load([XML Stream])  
' or doc.Load([XML File Path])
' or doc.LoadXml([XML String])

To remove the prolog element, we can remove the first child Node of the XmlDocument:

doc.RemoveChild(doc.FirstChild)

Since the Root element (ATT_ADDR_VAL_RESP) needs to be preserved (as in the sample result), while its Attributes should be removed, we can use the XmlNode.Attributes collection's RemoveAll() method to perform the clean-up:

doc.FirstChild.Attributes.RemoveAll()

If the Root element is not really required, we could also use the JsonConvert.SerializeXmlNode overload that allows to specify whether the Root element should be preserved:

Dim json = JsonConvert.SerializeXmlNode(doc, Formatting.Indented, True)

The last argument specifies that the Root element should be omitted.

The first child Node of the Root element also contains Arguments that need to be removed:

For Each childNode As XmlNode in doc.FirstChild.ChildNodes
    childNode.Attributes.RemoveAll()
Next

All parts combined, using Json.NET to serialize the XML to a JSON string:

Dim doc = New XmlDocument()
doc.Load([XML Stream])  

' FirstChild is the prolog element
doc.RemoveChild(doc.FirstChild)

' Now FirstChild is the XML Root element
doc.FirstChild.Attributes.RemoveAll()

For Each childNode As XmlNode in doc.FirstChild.ChildNodes
    childNode.Attributes.RemoveAll()
Next

' Or RemoveAllAttributes(doc)

Dim json = JsonConvert.SerializeXmlNode(doc, Formatting.Indented)

If all child Nodes need to be stripped of their Attributes, a recursive method can be used instead of a loop:

RemoveAllAttributes(doc)
(...)

Private Sub RemoveAllAttributes(XmlNode node)
    if node.Attributes IsNot Nothing Then node.Attributes.RemoveAll()
    For Each childNode As XmlNode In node.ChildNodes
        If childNode.Attributes IsNot Nothing Then childNode.Attributes.RemoveAll()
        If childNode.HasChildNodes Then
            RemoveAllAttributes(childNode)
        End if
    Next
End Sub
Find elsewhere
🌐
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.
🌐
Baeldung
baeldung.com › home › json › jackson › convert xml to json using jackson
Convert XML to JSON Using Jackson | Baeldung
January 8, 2024 - In this tutorial, we’ll see how to convert an XML message to JSON using Jackson.
🌐
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.
🌐
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.
🌐
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.
🌐
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, ...
🌐
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.
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.

🌐
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.