Retrieving JSON Object Literal from HttpServletRequest
Asked Answered
R

8

70

I am writing code that needs to extract an object literal posted to a servlet. I have studied the API for the HttpServletRequest object, but it is not clear to me how to get the JSON object out of the request since it is not posted from a form element on a web page.

Raceme answered 10/10, 2009 at 18:57 Comment(3)
Your question is confusing. Please show the JavaScript code (or whatever it might be) that causes something to be POSTed to the servlet, if it isn't a form. If you're looking for some built-in J2EE method to understand JSON object literals, there is none.Hilariahilario
Is your problem that you are trying to send a json object from the browser to the servlet, and you can't get the information on the servlet?Pronty
See also more popular #3832180Archle
P
68

are you looking for this ?

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = request.getReader();
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } finally {
        reader.close();
    }
    System.out.println(sb.toString());
}
Powerhouse answered 30/3, 2010 at 15:1 Comment(1)
This method do convert json representation into a string, but I think it is probably not the best way to handle json data.Auxesis
L
59

This is simple method to get request data from HttpServletRequest using Java 8 Stream API:

String requestData = request.getReader().lines().collect(Collectors.joining());
Laspisa answered 22/2, 2017 at 6:26 Comment(3)
This deserves more attention! Simplest solution in my opinion.Totemism
I get java.lang.IllegalStateException: STREAMED when calling getReader(). Any tips ?Tenancy
from inside org.eclipse.jetty.server.RequestTenancy
F
44

make use of the jackson JSON processor

 ObjectMapper mapper = new ObjectMapper();
  Book book = mapper.readValue(request.getInputStream(),Book.class);
Farina answered 9/12, 2014 at 17:23 Comment(3)
This is perfect! You rock!Dina
@Clyde D'Cruz How to use this while using HttpExchange..??Circumcise
Work for me well<3Vocable
E
31

The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:

BufferedReader reader = request.getReader();
Gson gson = new Gson();

MyBean myBean = gson.fromJson(reader, MyBean.class);
Endoderm answered 27/2, 2013 at 10:2 Comment(0)
E
23

There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request

String jsonString = IOUtils.toString(request.getInputStream());

Then you can do whatever you want, convert it to JSON or other object with Gson, etc.

JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
Embalm answered 30/4, 2015 at 6:56 Comment(3)
IOUtils.toString is Deprecated I used "String jsonString = new String(ByteStreams.toByteArray(request.getInputStream()))"Riannon
@Riannon this post is from 2015 and the question from 2009, stuff gets oldEmbalm
@Riannon The JavaDocs for the deprecated method offer IOUtils.toString(InputStream input, Charset charset) as replacement. This method buffers the input internally, so there is no need to use a BufferedInputStream etc. So essentially it is the same method as previous, the only difference is that it has one more parameter - Charset charset.Kierkegaard
A
5

If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..

If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.

Alarmist answered 28/6, 2010 at 16:48 Comment(0)
B
0

Converting the retreived data from the request object to json object is as below using google-gson

Gson gson = new Gson();
ABCClass c1 = gson.fromJson(data, ABCClass.class);

//ABC class is a class whose strcuture matches to the data variable retrieved
Bard answered 8/8, 2011 at 10:22 Comment(1)
Did you test this? It doesn't work. java.lang.IllegalArgumentException: class 'HttpServletRequest' declares multiple JSON fields named 'logger'.Nicolettenicoli
C
0

Use following dependencies

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.10.1</version>
</dependency>

Version can be any latest version

We can process Json input with following line of code

BufferedReader reader = request.getReader();
Gson gson = new Gson();
MyBean myBean = gson.fromJson(reader, MyBean.class);
Cordilleras answered 9/6, 2023 at 3:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.