You can deal with this attribute in this way -

inputStream = XMLtoJsonConverter.class.getClassLoader().getResourceAsStream("simple.xml");
String xml = IOUtils.toString(inputStream);
System.out.println(org.json.XML.toJSONObject(xml).toString(4));

If you want to go into depth of xml to json serialization look at this. while using this, you just want to create a pojo classes of xml structure nothing more than that.

Take a look at below code -

JacksonDeserializer.java -

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.IOException;
import java.net.URL;
import java.util.List;


public class JacksonDeserializer {

    private List<Item> item;
    private XmlMapper xmlMapper = null;
    private SimpleModule module = null;
    private Channel ch = null;

    public List<Item> getItem() {
        return item;
    }

    public void setItem(List<Item> item) {
        this.item = item;
    }

    public void readXML() throws IOException {
        xmlMapper = new XmlMapper();
        module = new SimpleModule();
        ch = new Channel();
        module.addDeserializer(List.class, ch.new ChannelDeserializer());
        xmlMapper.registerModule(module);
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        URL url = new URL("some xml data available on url");
        Rss rss = xmlMapper.readValue(url, Rss.class);//you can provide xml file also
        Channel channel = rss.getChannel();
        JacksonDeserializer obj = new JacksonDeserializer();
        item = channel.getItem();
        obj.setItem(item);
    }
}

Rss.java -

public class Rss {

    private Channel channel;

    public Rss() {
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }
}

Channel.java -

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Channel {

    private List<Item> item = new ArrayList();

    public Channel() {
    }

    public List<Item> getItem() {
        return item;
    }

    public void setItem(List<Item> item) {
        this.item = item;
    }

    public class ChannelDeserializer extends JsonDeserializer<List<Item>> {

        @Override
        public List<Item> deserialize(JsonParser jp, DeserializationContext arg1) throws IOException, JsonProcessingException {
            JsonNode jsonNode = jp.getCodec().readTree(jp);

            String title = jsonNode.get("title").asText();
            String link = jsonNode.get("link").asText();
            String description = jsonNode.get("description").asText();
            String pubDate = jsonNode.get("pubDate").asText();
            String source = jsonNode.get("source").path("").asText();
            Item i = new Item(title, link, description, pubDate, source);
            item.add(i);
            return item;
        }
    }
}

Item.java -

public class Item {

    private String title;
    private String link;
    private String description;
    private String pubDate;
    private String source;

    public Item() {
    }

    public Item(String title, String link, String description, String pubDate, String source) {
        this.title = title;
        this.link = link;
        this.description = description;
        this.pubDate = pubDate;
        this.source = source;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPubDate() {
        return pubDate;
    }

    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }
}
Answer from ketan on Stack Overflow
Top answer
1 of 1
1

You can deal with this attribute in this way -

inputStream = XMLtoJsonConverter.class.getClassLoader().getResourceAsStream("simple.xml");
String xml = IOUtils.toString(inputStream);
System.out.println(org.json.XML.toJSONObject(xml).toString(4));

If you want to go into depth of xml to json serialization look at this. while using this, you just want to create a pojo classes of xml structure nothing more than that.

Take a look at below code -

JacksonDeserializer.java -

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.IOException;
import java.net.URL;
import java.util.List;


public class JacksonDeserializer {

    private List<Item> item;
    private XmlMapper xmlMapper = null;
    private SimpleModule module = null;
    private Channel ch = null;

    public List<Item> getItem() {
        return item;
    }

    public void setItem(List<Item> item) {
        this.item = item;
    }

    public void readXML() throws IOException {
        xmlMapper = new XmlMapper();
        module = new SimpleModule();
        ch = new Channel();
        module.addDeserializer(List.class, ch.new ChannelDeserializer());
        xmlMapper.registerModule(module);
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        URL url = new URL("some xml data available on url");
        Rss rss = xmlMapper.readValue(url, Rss.class);//you can provide xml file also
        Channel channel = rss.getChannel();
        JacksonDeserializer obj = new JacksonDeserializer();
        item = channel.getItem();
        obj.setItem(item);
    }
}

Rss.java -

public class Rss {

    private Channel channel;

    public Rss() {
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }
}

Channel.java -

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Channel {

    private List<Item> item = new ArrayList();

    public Channel() {
    }

    public List<Item> getItem() {
        return item;
    }

    public void setItem(List<Item> item) {
        this.item = item;
    }

    public class ChannelDeserializer extends JsonDeserializer<List<Item>> {

        @Override
        public List<Item> deserialize(JsonParser jp, DeserializationContext arg1) throws IOException, JsonProcessingException {
            JsonNode jsonNode = jp.getCodec().readTree(jp);

            String title = jsonNode.get("title").asText();
            String link = jsonNode.get("link").asText();
            String description = jsonNode.get("description").asText();
            String pubDate = jsonNode.get("pubDate").asText();
            String source = jsonNode.get("source").path("").asText();
            Item i = new Item(title, link, description, pubDate, source);
            item.add(i);
            return item;
        }
    }
}

Item.java -

public class Item {

    private String title;
    private String link;
    private String description;
    private String pubDate;
    private String source;

    public Item() {
    }

    public Item(String title, String link, String description, String pubDate, String source) {
        this.title = title;
        this.link = link;
        this.description = description;
        this.pubDate = pubDate;
        this.source = source;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPubDate() {
        return pubDate;
    }

    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }
}
🌐
Baeldung
baeldung.com › home › json › jackson › convert xml to json using jackson
Convert XML to JSON Using Jackson | Baeldung
January 8, 2024 - XmlMapper xmlMapper = new XmlMapper(); JsonNode node = xmlMapper.readTree(xml.getBytes()); Having done this, we’ll have a JsonNode which has 3 children, as we expected: name, color, and petals.
Discussions

Convert xml to json with Java - Stack Overflow
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.... More on stackoverflow.com
🌐 stackoverflow.com
Quickest way to convert XML to JSON in Java - Stack Overflow
The only problem with JSON in Java is that if your XML has a single child, but is an array, it will convert it to an object instead of an array. This can cause problems if you dynamically always convert from XML to JSON, where if your example XML has only one element, you return an object, ... 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
Convert XML to Json natively?

If you are willing to learn a bit of python, this site walks you through what’s needed. I believe everything needed is distributed by RH. https://www.digitalocean.com/community/tutorials/python-xml-to-json-dict

More on reddit.com
🌐 r/redhat
1
1
September 6, 2024
🌐
GitHub
github.com › mohapatra-sambit › xml-to-json-converter
GitHub - mohapatra-sambit/xml-to-json-converter: Java-based XML to JSON Converter – A Generic and Flexible Tool for Converting XML Data into JSON Format with Ease
The recurrent_path field will not appear in the final converted JSON. ... The RECUR_ELEM is yet another keyword that is used to identify and map values from the XML entities to the JSON fields, specifically in the context of arrays. This defines the path of the XML element/attribute that comes in after the repeated element (defined against the recurrent_path field). In the above example, the element Item and the corresponding attribute Id appears for every repeated Line element.
Author   mohapatra-sambit
🌐
GitHub
github.com › lukas-krecan › json2xml
GitHub - lukas-krecan/json2xml: Java JSON to XML converter · GitHub
// convert JSON to DOM Node Node node = JsonXmlHelper.convertToDom(...); // do whatever on the DOM Node (eventually modify using XPATH it while respecting the type attributes) String json = JsonXmlHelper.convertToJson(node); This method has ...
Starred by 66 users
Forked by 28 users
Languages   Java
🌐
Novixys Software
novixys.com › blog › convert-xml-json
Converting Between XML and JSON Using JAXB and Jackson | Novixys Software Dev Blog
December 12, 2017 - When you need to convert XML to JSON and back, you can use JAXB with Jackson for the conversion. JAXB converts XML to java objects, and Jackson converts the same java objects to JSON.
Find elsewhere
🌐
GitHub
github.com › FasterXML › jackson › discussions › 140
XML to JSON with changing attribute name · FasterXML/jackson · Discussion #140
As an example: <root root_attr="1"> <child>FooBar</child> </root> BTW, We configured the XMLFactory to put '#text' in front of any text strings: XmlFactory xFactory = new XmlFactory(); xFactory.setXMLTextElementName("#text"); So the JSON would ...
Author   FasterXML
🌐
Blogger
javarevisited.blogspot.com › 2024 › 11 › how-to-convert-xml-to-json-in-java.html
How to convert XML to JSON in Java? Example
String soapmessageString = "<xml>yourStringURLorFILE</xml>"; JSONObject soapDatainJsonObject = XML.toJSONObject(soapmessageString); ... 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, ...
🌐
javaspring
javaspring.net › blog › convert-xml-to-json-java
Converting XML to JSON in Java: A Comprehensive Guide — javaspring.net
The process of converting XML to JSON involves parsing the XML document, traversing its structure, and creating a corresponding JSON object. This typically requires handling elements, attributes, and text values in the XML and mapping them appropriately to JSON keys and values. Jackson is a popular Java library for working with JSON and XML data.
🌐
Stleary
stleary.github.io › JSON-java › org › json › XML.html
XML
JSON does not does not like to distinguish between elements and attributes. Sequences of similar elements are represented as JSONArrays. Content text may be placed in a "content" member. Comments, prologs, DTDs, and ... A JSONObject containing the structured data from the XML string. ... Convert a well-formed (but not necessarily valid) XML into a JSONObject.
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.

🌐
Oracle
docs.oracle.com › middleware › 12213 › toplink › solutions › json.htm
16 Converting Objects to and from JSON Documents
Example 16-5 shows how to use bindings.json to map Customer and PhoneNumber classes to JSON. ... { "package-name" : "org.example", "xml-schema" : { "element-form-default" : "QUALIFIED", "namespace" : "http://www.example.com/customer" }, "java-types" : { "java-type" : [ { "name" : "Customer", "xml-type" : { "prop-order" : "firstName lastName address phoneNumbers" }, "xml-root-element" : {}, "java-attributes" : { "xml-element" : [ {"java-attribute" : "firstName","name" : "first-name"}, {"java-attribute" : "lastName", "name" : "last-name"}, {"java-attribute" : "phoneNumbers","name" : "phone-number"} ] } }, { "name" : "PhoneNumber", "java-attributes" : { "xml-attribute" : [ {"java-attribute" : "type"} ], "xml-value" : [ {"java-attribute" : "number"} ] } } ] } }
🌐
Quora
quora.com › How-can-I-convert-XML-to-JSON-in-Java
How to convert XML to JSON in Java - Quora
Answer (1 of 3): *If you are converting this in a mmaven project add the org.json dependency to your pom.xml. ** You can add Jackson jars too your Java project to perform this conversion. Hope the above points helped you.
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-xml-to-json-array-in-java
How to convert XML to JSON array in Java?
Gson is a third-party Java library developed by Google. It is used for converting Java objects to JSON and vice versa. To know more about Gson, refer to the Gson tutorial. We can use the Gson class of the Gson library to convert XML to JSON. The Gson class is a subclass of JsonElement class.
🌐
InterSystems
community.intersystems.com › post › convert-xml-json
Convert XML to JSON | InterSystems Developer Community | Java|JSON|XML
1 0 https://community.intersystems.com/post/convert-xml-json#comment-125266 ... Method XML2JSON(iXml As %String) [ Language = python ] { import xmltodict, json #; print(iXml) obj = xmltodict.parse(iXml) return(json.dumps(obj)) }
🌐
GroupDocs Cloud
blog.groupdocs.cloud › groupdocs cloud blog › how to convert xml to json in java using rest api
How to Convert XML to JSON in Java using REST API
April 6, 2023 - Learn how to convert XML to JSON in Java using REST API. Follow our step-by-step tutorial with just a few simple steps to get started today.
🌐
Delft Stack
delftstack.com › home › howto › java › xml to json java
How to Convert XML to JSON in Java | Delft Stack
March 11, 2025 - Learn how to convert XML to JSON in Java using popular libraries like org.json and Jackson. This comprehensive guide provides step-by-step code examples and detailed explanations to help you efficiently transform XML data into JSON format. Perfect for developers looking to enhance data interchange ...
🌐
Guru99
guru99.com › home › java tutorials › convert json to xml java using gson and jaxb with example
Convert JSON to XML Java using Gson and JAXB with Example
March 9, 2024 - JSON to XML in JAVA is converted by using JSONObject json = new JSONObject(str); String xml = XML.