0

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

14
  • What do you mean by json parameter? Commented Mar 15, 2014 at 20:08
  • I mean something like this: Content-Disposition: form-data; { "user_id" : 1, "value" : "Water", "typeCode" : "Searched" } Commented Mar 15, 2014 at 20:10
  • That is part of a header. Retrieve the header and parse out the JSON. Commented Mar 15, 2014 at 20:11
  • 1
    actually it is in the body of a request. My comment was just a sample. sorry for that Commented Mar 15, 2014 at 20:19
  • 1
    So the JSON is in the body? Just read the body (with one of many ways) and parse the JSON. Commented Mar 15, 2014 at 20:21

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

5 Comments

the problem is that I want to use the request in a filter, not in the controller so I cant use @RequestBody
This doesn't make any sense. To get the json from the request, you must use requestbody
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
@armin: I understand what you need. Take a look at my EDIT on the answer.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.