0

can anyone share code to convert json to xml this is the json that comes through the request

{'sector':'Europe','organization':'Bazz Market Unit UK','companyCode':'UK1_2020','approvalManager':'03000069','managementLevel1':'X11','approvalLimit':'500000','access Category':'FTeam','currency':'USD','comments':'Need this access so I can do my job properly'}

I need json to xml as well as vice- versa .Can any one help me out, I'd prefer code with no jar imports required.

Thanks in advance

Konstantin Pelepelin
  • 1,303
  • 1
  • 14
  • 29
zDroid
  • 426
  • 1
  • 11
  • 32
  • You want to parse this with Java? Or you want just the results? – sdrzymala Jun 05 '14 at 12:44
  • I'm not sure you are going to get this in Java without some imported lib. See here for an example of how to do it with a lib: [http://stackoverflow.com/a/19978281/584599](http://stackoverflow.com/a/19978281/584599) – Chad W Jun 05 '14 at 12:48
  • 2
    That json is not valid and can possible not be parsed because it has single instead of double quotes – Tim Jun 05 '14 at 14:08
  • Underscore-java library has a static methods U.jsonToXml(json) and U.xmlToJson(xml). – Valentyn Kolesnikov Mar 04 '20 at 06:04

3 Answers3

1

If you are using Java SE and can't use foreign JARs, and your JSON is always simple as the example you posted, you can parse it. Here's a short program that works for your example (but you will certainly have to adapt it if you have more complex JSON strings with more nesting levels and arrays):

public class SimpleJsonToXml {
    public static void main(String[] args) {
        String json = "{'sector':'Europe','organization':'Bazz Market Unit UK','companyCode':'UK1_2020','approvalManager':'03000069','managementLevel1':'X11','approvalLimit':'500000','access Category':'FTeam','currency':'USD','comments':'Need this access, so I can do my job properly'}";
        String jsonObject = json.replaceAll("\\{(.*)\\}", "$1");
        String[] childElements = jsonObject.split("(,)(?=(?:[^\']|\'[^\']*\')*$)");

        System.out.println("<root>");
        for (String item : childElements) {
            System.out.println(makeTag(item));
        }
        System.out.println("</root>");
    }

    public static String makeTag(String jsonProperty) {
        String[] element = jsonProperty.split("\\:");
        String tagName = element[0].replaceAll("[' ]", "");
        String tagValue = element[1].replace("'", "");
        return "    <"+tagName+">"+tagValue+"</"+tagName+">";
    }
}

It will print:

<root>
    <sector>Europe</sector>
    <organization>Bazz Market Unit UK</organization>
    <companyCode>UK1_2020</companyCode>
    <approvalManager>03000069</approvalManager>
    <managementLevel1>X11</managementLevel1>
    <approvalLimit>500000</approvalLimit>
    <accessCategory>FTeam</accessCategory>
    <currency>USD</currency>
    <comments>Need this access, so I can do my job properly</comments>
</root>

To convert XML back to JSON you can use the native Java XML tools and parsers (org.w3c.dom and org.xml.sax, for example) and won't need any external Jars.

If you are using at least Java EE 7, you can use the parsers in the javax.json package.

helderdarocha
  • 23,209
  • 4
  • 50
  • 65
  • how about these types of response jsons.. { "statusResponse": { "status": "failed", "code": "NOT_AUTHORIZED_FOR_MYBUY", "prescriptiveDiagnostic": "User is not authorized for myBuy. Please request access first." } } or { "statusResponse ": { "status": "success" }, "response": { } } – zDroid Jun 06 '14 at 10:20
  • It certainly is possible, but now we are moving toward a general solution (no longer "a simple json to xml conversion") and if we continue, we will end up reinventing a JSON Parser :) which is certainly a good programming exercise, but if you don't wish to reinvent the wheel, trying some existing packages or even incorporating the code (if you can't have foreign JARs) might be a better solution. Try this package: http://www.json.org/java/index.html It's very easy to use. Or use Java EE. – helderdarocha Jun 06 '14 at 14:54
1

I tried this and works pretty well for me...

json to xml -

JSON jsonObject = JSONSerializer.toJSON(json); 
    XMLSerializer xmlSerialized = (new XMLSerializer());
    xmlSerialized.setTypeHintsEnabled(false);
    String xml = xmlSerialized.write( jsonObject );

and xml to json

org.json.JSONObject object;
    String json = null;
    try {
        object = XML.toJSONObject(xml);
         json = object.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }

Hope this helps.. :)

zDroid
  • 426
  • 1
  • 11
  • 32
0

Underscore-java library has static method U.jsonToXml(json).

Valentyn Kolesnikov
  • 2,029
  • 1
  • 24
  • 31