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

4
  • You want to parse this with Java? Or you want just the results? Commented Jun 5, 2014 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 Commented Jun 5, 2014 at 12:48
  • 2
    That json is not valid and can possible not be parsed because it has single instead of double quotes Commented Jun 5, 2014 at 14:08
  • Underscore-java library has a static methods U.jsonToXml(json) and U.xmlToJson(xml). Commented Mar 4, 2020 at 6:04

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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": { <a successful response object> } }
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: json.org/java/index.html It's very easy to use. Or use Java EE.
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.. :)

Comments

0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.