[java] Converting JSON to XML in Java

I am new to json. I am having a program to generate xml from json object.

String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";  
    JSON json = JSONSerializer.toJSON( str );  
    XMLSerializer xmlSerializer = new XMLSerializer();  
    xmlSerializer.setTypeHintsCompatibility( false );  
    String xml = xmlSerializer.write( json );  
    System.out.println(xml); 

the output is:

<?xml version="1.0" encoding="UTF-8"?>
<o><array json_class="array"><e json_type="number">1</e><e json_type="number">2</e><e json_type="number">3</e></array><boolean json_type="boolean">true</boolean><double json_type="number">2.0</double><integer json_type="number">1</integer><name json_type="string">JSON</name><nested json_class="object"><id json_type="number">42</id></nested></o>

my biggest problem is how to write my own attributes instead of json_type="number" and also writing my own sub elements like .

This question is related to java xml json xpath

The answer is


For json to xml use the following Jackson example:

final String str = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";
ObjectMapper jsonMapper = new ObjectMapper();
JsonNode node = jsonMapper.readValue(str, JsonNode.class);
XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_1_1, true);
StringWriter w = new StringWriter();
xmlMapper.writeValue(w, node);
System.out.println(w.toString());

Prints:

<?xml version='1.1' encoding='UTF-8'?>
<ObjectNode>
  <name>JSON</name>
  <integer>1</integer>
  <double>2.0</double>
  <boolean>true</boolean>
  <nested>
    <id>42</id>
  </nested>
  <array>1</array>
  <array>2</array>
  <array>3</array>
</ObjectNode>

To convert it back (xml to json) take a look at this answer https://stackoverflow.com/a/62468955/1485527 .


If you want to replace any node value you can do like this

JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
xml.replace("old value", "new value");

If you have a valid dtd file for the xml then you can easily transform json to xml and xml to json using the eclipselink jar binary.

Refer this: http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html

The article also has a sample project (including the supporting third party jars) as a zip file which can be downloaded for reference purpose.


Transforming with XSLT 3.0 is the only proper way to do it, as far as I can tell. It is guaranteed to produce valid XML, and a nice structure at that. https://www.w3.org/TR/xslt/#json


Underscore-java library has static method U.jsonToXml(jsonstring). I am the maintainer of the project. Live example

import com.github.underscore.lodash.U;

public class MyClass {
    public static void main(String args[]) {
        String json = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";  
        System.out.println(json); 
        String xml = U.jsonToXml(json);  
        System.out.println(xml); 
    }
}

Output:

{"name":"JSON","integer":1,"double":2.0,"boolean":true,"nested":{"id":42},"array":[1,2,3]}
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <name>JSON</name>
  <integer number="true">1</integer>
  <double number="true">2.0</double>
  <boolean boolean="true">true</boolean>
  <nested>
    <id number="true">42</id>
  </nested>
  <array number="true">1</array>
  <array number="true">2</array>
  <array number="true">3</array>
</root>

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to xpath

Xpath: select div that contains class AND whose specific child element contains text XPath: difference between dot and text() How to set "value" to input web element using selenium? How to click a href link using Selenium XPath: Get parent node from child node What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing? How to use XPath preceding-sibling correctly Selenium and xPath - locating a link by containing text How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug? Concatenate multiple node values in xpath