Return JsonObject in spring restful webservice

I am using spring framework. I have a web service on a Wepsphere server like this

@RequestMapping (value="/services/SayHello2Me" , method=RequestMethod.GET, headers="Accept=application/json") @ResponseBody public JSONObject SayHello2Me(HttpServletRequest request) throws Exception { String input = (String) request.getParameter("name"); String output = "hello " + input + " :)"; JSONObject outputJsonObj = new JSONObject(); outputJsonObj.put("output", output); return outputJsonObj; } 

When I call it a Chrome form, for example http: // myserver / services / sayHello2Me? Name = 'baris', it returns me this error:

Error 404: SRVE0295E: Error Reported: 404

If I change annotations in my web service like

 @RequestMapping (value="/services/SayHello2Me") @ResponseBody public JSONObject SayHello2Me(HttpServletRequest request) throws Exception { String input = (String) request.getParameter("name"); String output = "hello " + input + " :)"; JSONObject outputJsonObj = new JSONObject(); outputJsonObj.put("output", output); return outputJsonObj; } 

then when I call it a Chrome form, like http: // myserver / services / sayHello2Me? name = 'baris', it returns me this error:

Error 406: SRVE0295E: Error Reported: 406

There is a jsonobject problem because if I return String insted jsonobject in the same web service, it returns me successfully.

How can I return Jsonobject to spring restful webservice?

+5
source share
2 answers

406-Unacceptable Answer

you should use return outputJsonObj.toString(); lower as

 @RequestMapping (value="/services/SayHello2Me") @ResponseBody public String SayHello2Me(HttpServletRequest request) throws Exception { String input = (String) request.getParameter("name"); String output = "hello " + input + " :)"; JSONObject outputJsonObj = new JSONObject(); outputJsonObj.put("output", output); return outputJsonObj.toString(); } 
+6
source

You can use jackson:

 @RequestMapping (value="/services/SayHello2Me" , method=RequestMethod.GET, produces="application/json") 
+1
source

All Articles