How to read a json object which is being sent as part of http post request using gson

195 views
Skip to first unread message

nikhil reddy

unread,
May 15, 2013, 4:38:40 PM5/15/13
to googl...@googlegroups.com
Can anyone cite some example of how to read a json object which is being sent as part of http post request using gson

I could only read it using 

BufferedReader reader = req.getReader();

            req.getParameterMap();

            StringBuilder sb = new StringBuilder();

            String line = reader.readLine();

            while (line != null) {

                sb.append(line + "\n");

                line = reader.readLine();

}

            reader.close();

            String data = sb.toString();


Is there any specific way to retreieve ...why am i unable to retreive using req.getParameter("ANYTHING");

Any advice is greatly appreciated

Joel Leitch

unread,
May 15, 2013, 5:14:55 PM5/15/13
to googl...@googlegroups.com
Hi Nikhil,
I am assuming that you are sending a pure JSON request as the request body. If that is true then hopefully it is being send with a content-type of "application/json". The req.getParameter("anything") assumes a content type of "application/x-www-form-urlencoded" or a normal HTTP GET (for URL parameters).

If you are sending a JSON request to your server then it would best to read in the JSON structure as follows:
JsonElement jsonTree = gson.fromJson(req.getReader(), JsonElement.class);

Or better yet, if you have some class Foo that represents the JSON structure then you can do the following:
Foo foo = gson.fromJson(req.getReader(), Foo.class);

For writing out a JSON response, it can be done as follows:
resp.setContentType("application/json");
gson.toJson(foo, resp.getWriter());
Reply all
Reply to author
Forward
0 new messages