-1

My Json Object from postman:

{
    "sender":"hello"
}

My servlet dopost method:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
     throws ServletException, IOException {

    Gson gs = new Gson();
    String chatId = gs.fromJson(req.getParameter("sender"), String.class);
    JSONObject obj = new JSONObject(); 

    JSONArray arr= new JSONArray();
    try {
        obj.put("name", chatId);
        arr.add(obj);
    }       
    finally {
    }
    resp.setContentType("application/json");
    resp.setCharacterEncoding("utf-8");
    resp.getWriter().println(arr);
}   

What am I doing wrong?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Kanishk Gupta
  • 369
  • 2
  • 10
  • is your chatId non-null? Could you please check it out first? – gvlachakis Mar 29 '17 at 08:59
  • `req.getParameter("sender")` attempts to read a sender HTTP parameter, not a JSON "sender" entry in the JSON object in the body of the request. – mkl Mar 29 '17 at 19:55

2 Answers2

0

I think JSON will come in request body. Refer Get the POST request body from HttpServletRequest to read the requestbody from HttpServletRequest.

Community
  • 1
  • 1
Jaydeep Rajput
  • 3,605
  • 17
  • 35
0

What I was doing wrong was not using Gson properly.

HashMap<String,String> map = new Gson().fromJson( new JsonReader(request.getReader()), new TypeToken<HashMap<String, String>>(){}.getType());

This code directly converted my Json body into a Hashmap.

Kanishk Gupta
  • 369
  • 2
  • 10