0

I want to get Json key values from HttpServletRequest.

My Java code is given below

import java.io.BufferedReader;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

@WebServlet("/Service")
public class Service extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                jb.append(line);
            }
        } catch (Exception e) {
        }

        try {
            JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
            String email = jsonObject.getString("email");
        } catch (Exception e) {
        }
    }
}

Post JSON

{
    "email": "test@xyz.com",
    "fname": "test01"
}

I am getting below JSON output using JSONObject jsonObject = HTTP.toJSONObject(jb.toString());

{"\"test@xyz.com\",\t\"fname\"":"\"test01\"}","Request-URI":"email","Method":"{","HTTP-Version":":"}

I am not getting any value using String email = jsonObject.getString("email");

I am using Eclipse Mars 1 using JAVA.

user3441151
  • 1,880
  • 6
  • 35
  • 79

1 Answers1

-1

How are you passing your json in?

If you are passing it in as Content-Type: application/x-www-form-urlencoded, then the above won't work - you should use something like

JSONObject jObj = new JSONObject(request.getParameter("mydata"));

where mydata is the name of the HTML form field.

If you use Content-Type: application/json, the code you provided should work. Can you confirm that?

It's worth anyway to output the contents of jb.toString() in the servlet, so you can see what came into it before trying to parse it as JSON if it's invalid already.

If you can use curl, test your code with:

curl http://localhost:8080/ -H "Content-Type: application/json" -X POST -d '{"email": "test@xyz.com","fname": "test01"}'

or the code such as in the last reference below.

References:

Community
  • 1
  • 1
levant pied
  • 3,886
  • 5
  • 37
  • 56