|
|
How to handle request with content-type=application/json
I'd like to be able to handle JSON requests with the Content-Type in the header set to application/json, instead of uclencoded form parameters. The client doesn't use DWR, so that's out, and I'm aware of JSONView, but AFAIK that's only for the response side. Does anyone have a suggestion of how to handle this?
Thanks,
Mike Monette
Hi Mike,
Well when I'm sending JSON I use the library from to encode it.
There's also methods for creating a java object graph from a JSON string.
Take a look -
java/index.html
Andy.
Thanks for replying. My problem, though, isn't with sending JSON from the server (ie putting it in the response). It's receiving JSON in the request with a Content-Type of application/json.
Are you asking how to get JSON string into an object graph that you can work with?
In your controller call getReader() on the fromServletRequest parameter, read the bytes into a string, for example, requestBody then call -
JSONObject requestObject = new JSONObject(requestBody);
Then, assuming you know the structure of the data than can be sent in the JSON string, you just call getters on the requestObject, e.g. If the request contains a field called 'comments'
String commentsField = jsonObj.get(quot;commentsquot;);
After processing it, just return whatever response is expected by the client of course.
Andy.
This is exactly what I was looking for. Thanks, Andy! |
|