21

Are there existing JARs available to convert from JSON to XML?

dacracot
  • 22,002
  • 26
  • 104
  • 152

9 Answers9

26

You can create a JSONObject, and then convert it to XML using the XML class in the org.json namespace

Wrapping the json string in the object is as easy as passing it in its constructor

JSONObject o = new JSONObject(jsonString);

Then you can get it in XML format using the XML class, like so:

String xml = org.json.XML.toString(o);
dbreaux
  • 4,982
  • 1
  • 25
  • 64
juan
  • 80,295
  • 52
  • 162
  • 195
  • 6
    That is amazingly simple, thank you! – Jon Feb 13 '13 at 09:53
  • Can you please elaborate??i mean do i have to use external jars?eclipse won't recognize these commands – Ankit Srivastava Aug 19 '13 at 16:44
  • You can try this: http://mvnrepository.com/artifact/org.codeartisans/org.json/20130603 – Browny Lin Sep 24 '13 at 16:40
  • 1
    @AnkitSrivastava, the source java files for the classes **JSONObject** & **XML** can be downloaded from https://github.com/douglascrockford/JSON-java (json.org/java). You still have to make the jar yourself though. But if you're working with Google App Engine, the classes JSONObject & XML can be found in `com.google.appengine.labs.repackaged.org.json.*` – Abel Callejo Jan 06 '14 at 04:02
  • JSONObject jsonObject = new JSONObject(json.toString())...This line throws an error saying "no suitable constructor found for JSONObject(String)" – Paras Singh Dec 14 '17 at 06:48
14

Not a Java, but a pure XSLT 2.0 implementation:

Have a look at the f:json-document() from the FXSL 2.x library.

Using this function it is extremely easy to incorporate JSon and use it just as... XML.

For example, one can just write the following XPath expression:

f:json-document($vstrParam)/Students/*[sex = 'Female']

and get all children of Students with sex = 'Female'

Here is the complete example:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:f="http://fxsl.sf.net/"
 exclude-result-prefixes="f xs"
 >
 <xsl:import href="../f/func-json-document.xsl"/>

 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="vstrParam" as="xs:string">
{

  "teacher":{
    "name":
      "Mr Borat",
    "age":
      "35",
    "Nationality":
      "Kazakhstan"
             },


  "Class":{
    "Semester":
      "Summer",
    "Room":
      null,
    "Subject":
      "Politics",
    "Notes":
      "We're happy, you happy?"
           },

  "Students":
    {
      "Smith":
        {"First Name":"Mary","sex":"Female"},
      "Brown":
        {"First Name":"John","sex":"Male"},
      "Jackson":
        {"First Name":"Jackie","sex":"Female"}
    }
    ,


  "Grades":

    {
      "Test":
      [
        {"grade":"A","points":68,"grade":"B","points":25,"grade":"C","points":15},

        {"grade":"C","points":2, "grade":"B","points":29, "grade":"A","points":55},

        {"grade":"C","points":2, "grade":"A","points":72, "grade":"A","points":65}
       ]
    }


}
 </xsl:variable>

 <xsl:template match="/">
    <xsl:sequence select=
     "f:json-document($vstrParam)/Students/*[sex = 'Female']"/>

 </xsl:template>
</xsl:stylesheet>

When the above transformation is applied on any XML document (ignored), the correct result is produced:

<Smith>
   <First_Name>Mary</First_Name>
   <sex>Female</sex>
</Smith>
<Jackson>
   <First_Name>Jackie</First_Name>
   <sex>Female</sex>
</Jackson>
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
  • Looks great. But I tried and f:json-document() is always returning an empty document. I posted about this in the SF.net forum: https://sourceforge.net/forum/message.php?msg_id=7385342 – avernet May 11 '09 at 07:58
  • There is an example how to use this fuction. It is the testFunc-json-document.xsl file in the Tests folder: http://fxsl.cvs.sourceforge.net/viewvc/fxsl/fxsl-xslt2/Tests/testFunc-json-document.xsl?revision=1.1&view=markup When applied on any XML file (not used) this transformation produces the correct result. One potential factor that could cause your problem is the use of relatively old version of Saxon -- please use a 9.x version of Saxon. Also, the link in your message is unreachable. – Dimitre Novatchev May 11 '09 at 13:51
3

One more possibility: Jettison, http://jettison.codehaus.org can expose Json via XML parsing interface (stax XMLStreamReader), which allows integration with systems that only understand XML. It requires use of a convention (badgerfish, or whatever the other one was called).

XStream, for example, uses Jettison (or at least Badgerfish convention) to allow use of JSON.

But the question itself is bit vague: while you can always convert from one to the othe (it is a very trivial thing to do really), XML and JSON are not equivalent: there is no one-to-one lossless generic mapping. Hence, the question is: what are you planning to do with results, how is resulting xml to be used?

StaxMan
  • 113,358
  • 34
  • 211
  • 239
2

http://json-lib.sourceforge.net/

  • the points above about no completely foolproof one-one mapping are valid, but I have had a good experience with converting xml to json using the above library.
okredo
  • 61
  • 3
2

You may want to try XStream. Take a look at http://x-stream.github.io/faq.html#JSON.

facundofarias
  • 2,973
  • 28
  • 27
Antonio
  • 2,406
  • 1
  • 16
  • 8
1

Conversion Box!!!

I am using the JSON that Dimitre has pasted in his reply and have converted into an XML. Lets see if it works for you .....

import org.json.me.JSONObject;

import cjm.component.cb.xml.ToXML;

public class Test
{
public static void main(String[] args)
{
    try
    {
        JSONObject objectJSON = new JSONObject();

        objectJSON.put("ROOT", (new JSONObject("{\"teacher\":{\"name\":\"Mr Borat\",\"age\":\"35\",\"Nationality\":\"Kazakhstan\"},\"Class\":{\"Semester\":\"Summer\",\"Room\":null,\"Subject\":\"Politics\",\"Notes\":\"We're happy, you happy?\"},\"Students\":{\"Smith\":{\"FirstName\":\"Mary\",\"sex\":\"Female\"},\"Brown\":{\"FirstName\":\"John\",\"sex\":\"Male\"},\"Jackson\":{\"FirstName\":\"Jackie\",\"sex\":\"Female\"}},\"Grades\":{\"Test\":[{\"grade\":\"A\",\"points\":68,\"grade\":\"B\",\"points\":25,\"grade\":\"C\",\"points\":15},{\"grade\":\"C\",\"points\":2,\"grade\":\"B\",\"points\":29,\"grade\":\"A\",\"points\":55},{\"grade\":\"C\",\"points\":2,\"grade\":\"A\",\"points\":72,\"grade\":\"A\",\"points\":65}]}}")));

        System.out.println("JSON: " + objectJSON);

        StringBuilder xml = new ToXML().convertToXML(objectJSON, true); // Conversion Box!!!!

        System.out.println("XML: " + xml);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

Output:

JSON: {"ROOT":{"Students":{"Brown":{"FirstName":"John","sex":"Male"},"Jackson":{"FirstName":"Jackie","sex":"Female"},"Smith":{"FirstName":"Mary","sex":"Female"}},"Class":{"Subject":"Politics","Room":null,"Semester":"Summer","Notes":"We're happy, you happy?"},"Grades":{"Test":[{"points":15,"grade":"C"},{"points":55,"grade":"A"},{"points":65,"grade":"A"}]},"teacher":{"age":"35","name":"Mr Borat","Nationality":"Kazakhstan"}}}
 -------- JSON Detected -------- 
 -------- XML created Successfully -------- 
XML: <ROOT><Students><Brown><FirstName>John</FirstName><sex>Male</sex></Brown><Jackson><FirstName>Jackie</FirstName><sex>Female</sex></Jackson><Smith><FirstName>Mary</FirstName><sex>Female</sex></Smith></Students><Class><Subject>Politics</Subject><Room>null</Room><Semester>Summer</Semester><Notes>We're happy, you happy?</Notes></Class><Grades><Test><LIST_ELEMENT_Test><points>15</points><grade>C</grade></LIST_ELEMENT_Test><LIST_ELEMENT_Test><points>55</points><grade>A</grade></LIST_ELEMENT_Test><LIST_ELEMENT_Test><points>65</points><grade>A</grade></LIST_ELEMENT_Test></Test></Grades><teacher><age>35</age><name>Mr Borat</name><Nationality>Kazakhstan</Nationality></teacher></ROOT>
1

You can try https://github.com/lukas-krecan/json2xml that provides simple JSON to XML conversion. It takes Jackson JSON parser and usees it to emit SAX events.

Lukas
  • 13,606
  • 9
  • 31
  • 40
0

StAXON can convert JSON to XML using either XSLT with default templates or StAX event API https://github.com/beckchr/staxon/wiki/Converting-JSON-to-XML

Here's a simple example:

INPUT FILE:

{
    "container":[
        {
            "someString":"xxxxx",
            "someInteger":123,
            "someArrayElem":[
                {
                    "key":1111,
                    "value":"One"
                },
                {
                    "key":2222,
                    "value":"Two"
                }
            ]
        }
    ]
}

Imports + code:

import de.odysseus.staxon.json.JsonXMLConfig;
import de.odysseus.staxon.json.JsonXMLConfigBuilder;
import de.odysseus.staxon.json.JsonXMLInputFactory;
import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import java.io.StringWriter;

StringWriter stringWriter = new StringWriter();
JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).prettyPrint(false).build();
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(getClass().getClassLoader().getResourceAsStream("input.json"));
XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(stringWriter);
writer = new PrettyXMLEventWriter(writer);
writer.add(reader);
String xml = stringWriter.getBuffer().toString();

OUTPUT:

<?xml version="1.0" encoding="UTF-8"?>
<container>
    <someString>xxxxx</someString>
    <someInteger>123</someInteger>
    <someArrayElem>
        <key>1111</key>
        <value>One</value>
    </someArrayElem>
    <someArrayElem>
        <key>2222</key>
        <value>Two</value>
    </someArrayElem>
</container>
Mark
  • 821
  • 7
  • 14
0

You can use json-lib, it provides bidirectional conversion.

Marcus
  • 2,128
  • 20
  • 22
Bhushan Bhangale
  • 10,921
  • 5
  • 43
  • 71