2

I have a servlet that takes a parameter from the request and sends a JsonObject as a response.

My problem that every time that I tried to use the PrintWriter class (I tried even to print simple string as a test), the servlet starts but never returns a response. My second problem is that I get the following exception:

java.lang.ClassNotFoundException: org.json.JSONObject

What package contains the JsonObject?

The servlet code:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String user = request.getParameter("param1"); // I need this later ...
    System.out.println("do get called ");
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
    org.json.JSONObject json = new org.json.JSONObject();
    try {
        json.put("Mobile",123);
        json.put("Name", "ManojSarnaik");
        out.print(json.toString());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        out.flush();
    } finally{
        out.flush();
    }
}
1
  • I'd guess that your two issues are one in the same. You are not getting a response because your method is throwing an exception. The library you are looking for (judging by the org.json package) is: github.com/douglascrockford/JSON-java Commented Nov 9, 2015 at 20:35

1 Answer 1

6

Your code should be worked fine except for this exception 'ClassNotFoundException' that means that the org.json.JSONObject aren't in the classpath and on the build for project, make sure that you import by maven:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20150729</version>
</dependency>

or JAR file for the class JSONObject.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.