简体   繁体   中英

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 '<'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM