61

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 .

2
  • vinod,Have you got the solution for the above question, "Writing your own attributes to XML tags generated from json".? I'm also looking for the solution, if you found that, please post that in this thread. Thanks in advance.
    – Malleswari
    Jul 10, 2014 at 12:35
  • @Malleswari You may convert JSON to a map, modify it and then convert back. Jan 11, 2020 at 5:29

6 Answers 6

136

Use the (excellent) JSON-Java library from json.org then

JSONObject json = new JSONObject(str);
String xml = XML.toString(json);

toString can take a second argument to provide the name of the XML root node.

This library is also able to convert XML to JSON using XML.toJSONObject(java.lang.String string)

Check the Javadoc

Link to the the github repository

POM

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160212</version>
</dependency>

original post updated with new links

13
  • 1
    thanks for it. how to write json object to add attrubute to element like <Private Provider="AB"/>
    – vinod
    Nov 14, 2013 at 13:04
  • I guess the only way will be to deserialize the JSON to a (custom) Java Object. Then, using a framework like XMLBeans or XStream and with the help of annotations, specify which property goes as element and which goes as attribute Nov 14, 2013 at 14:27
  • Alternatively, use the XML from the simple two lines above and apply an XSLT to it Nov 14, 2013 at 14:29
  • 1
    Very convenient for simple one-to-one JSON to XML conversion. Dec 9, 2015 at 9:13
  • 2
    This does not work for me, I get invalid xml out of valid json. Jan 11, 2016 at 10:22
9

Underscore-java library has static method U.jsonToXml(jsonstring). Live example

import com.github.underscore.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]}";
        String xml = U.jsonToXml(json, U.JsonToXmlMode.REMOVE_ATTRIBUTES);
        System.out.println(xml);
    }
}

Output:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <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>
</root>
3
  • thx for this. especially with mixed json object array structure its much easier than the top rated answer
    – DubZ
    Oct 24, 2019 at 11:11
  • @Valentyn - How to add soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" while converting Json to XML ?
    – Prateek
    Dec 24, 2019 at 9:10
  • 1
    Thanks. This is best solution in 2020. Some other libraries not work. Dec 11, 2020 at 22:21
7

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);
ObjectWriter ow = xmlMapper.writer().withRootName("root");
StringWriter w = new StringWriter();
ow.writeValue(w, node);
System.out.println(w.toString());

Prints:

<?xml version='1.1' encoding='UTF-8'?>
<root>
  <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>
</root>

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

3
  • You'd better show how to override "ObjectNode". Oct 22, 2021 at 9:56
  • 1
    @SimonLogic Good hint! 'Feature' added.
    – jschnasse
    Oct 25, 2021 at 6:28
  • Is there a way to convert an array of objects in the JSON to a wrapped list in the XML? Say the JSON has "objects": [{"value": 1}, {"value": 2}], is it possible to get <objects><object><value>1</value></object><object><value>2</value></object></objects>? Aug 8, 2022 at 21:01
4

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.

0

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

1
-2

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");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.