VGH
VGH

Reputation: 425

Producing both JSON and XML response in Java RESTful web service using Jersey

We've a method which returns a String response which is formed using org.w3c.dom.Document. Hence default response is in XML format. Now we need to support JSON response as well. Since we are manually preparing XML response using org.w3c.dom.Document instead of using POJO and annotate it with @XmlRootElement, and we can't modify the legacy code, how to support both JSON and XML response types ?

@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})

Just by annotating the method like above and using header Accept : application/json in request results in error : Unexpected '<'

Upvotes: 0

Views: 1168

Answers (1)

Saurabh Jhunjhunwala
Saurabh Jhunjhunwala

Reputation: 2922

I hope you are looking for

public class Main {

    public static int PRETTY_PRINT_INDENT_FACTOR = 4;
    public static String TEST_XML_STRING =
        "<?xml version=\"1.0\" ?><test attrib=\"moretest\">Turn this to JSON</test>";

    public static void main(String[] args) {
        try {
            JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
            String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
            System.out.println(jsonPrettyPrintString);
        } catch (JSONException je) {
            System.out.println(je.toString());
        }
    }
}

You can use the logic to convert the XML response to JSON, but do remember to add an if condition, checking the response type.

Upvotes: 1

Related Questions