views:

522

answers:

3

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.

Any insight is appreciated.

Thanks.

A: 

I'm facing with the same problem: "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?"

Any comments?

Leandro
+1  A: 

are you looking for this ?

    @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    BufferedReader reader = request.getReader();
    StringBuilder sb = new StringBuilder();
    String line = reader.readLine();
    while (line != null) {
        sb.append(line + "\n");
        line = reader.readLine();
    }
    reader.close();
    String data = sb.toString();

    System.out.println(data);
}
A: 

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.

arunjitsingh