I am trying to extract json parameters from a request but I couldn't. By getParameter method in servletRequest, I could just get the post parameter. The json parameters don't have any name so by request.getParameter("?") I can't fill the question mark
-
What do you mean by json parameter?Sotirios Delimanolis– Sotirios Delimanolis2014-03-15 20:08:01 +00:00Commented Mar 15, 2014 at 20:08
-
I mean something like this: Content-Disposition: form-data; { "user_id" : 1, "value" : "Water", "typeCode" : "Searched" }armin– armin2014-03-15 20:10:28 +00:00Commented Mar 15, 2014 at 20:10
-
That is part of a header. Retrieve the header and parse out the JSON.Sotirios Delimanolis– Sotirios Delimanolis2014-03-15 20:11:45 +00:00Commented Mar 15, 2014 at 20:11
-
1actually it is in the body of a request. My comment was just a sample. sorry for thatarmin– armin2014-03-15 20:19:11 +00:00Commented Mar 15, 2014 at 20:19
-
1So the JSON is in the body? Just read the body (with one of many ways) and parse the JSON.Sotirios Delimanolis– Sotirios Delimanolis2014-03-15 20:21:56 +00:00Commented Mar 15, 2014 at 20:21
|
Show 9 more comments
1 Answer
If you have prepared a java class in the exact structure like the json, do:
@RequestMapping(...)
public mycontrollerfunc(@RequestBody YourJsonClass body){}
If not, and you want the json as a string, do:
@RequestMapping(...)
public mycontrollerfunc(@RequestBody String body){}
EDIT
If you need to extract the request body (which is what you refer to as "Json Parameter") from a method who can't use @RequestBody and only has access to HttpServletRequest, you can do the following:
String jsonFromRequestBody = CharStreams.toString(request.getReader());
In this case, request has to be HttpServletRequest, so you might need to cast it if you're in a Filter, something like:
HttpServletRequest request = (HttpServletRequest) req;
5 Comments
armin
the problem is that I want to use the request in a filter, not in the controller so I cant use @RequestBody
Shay Elkayam
This doesn't make any sense. To get the json from the request, you must use requestbody
armin
I want to use input validation in a filter so I must to get the json body in a filter. Unfortunately it is not possible to use @RequestBoduy in the filter
Shay Elkayam
@armin: I understand what you need. Take a look at my EDIT on the answer.
armin
I tried to read it by getReader() but the problem was that because more than once spring tried to use it, I got an exception which is said that it cant be used more than one time