2

I am trying to send JSON data as a response from a servlet, to Javascript code in my JSP page. I send the data back using the code response.getWriter.write(jsondata);, where jsondata is the JSON object. What I get back in my Javascript as response is something like [object Object], which is not what I need. Can someone help me understand whats going wrong here?

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    Map<String, Object> data = new HashMap<String, Object>();
    data.put("success", true);
    data.put("message", "Hello World!");
    data.put("param", request.getParameter("user"));

    // Write response data as JSON.
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    System.out.println(new Gson().toJson(data));
    response.getWriter().write(new Gson().toJson(data));
}

Also, please note that when I use sysout to print the json object it works fine, but when I write it to the response object it gives back [object Object] on the Javascript side.

Perception
  • 79,279
  • 19
  • 185
  • 195
  • Your code seems fine to me. Can you elaborate on `[object Object]`? Have you checked what is exactly being sent through the network using Firebug or any other similar tool? – mindas Mar 07 '13 at 21:57
  • Well can you tell us what is displayed when you hit the url to this servlet in a browser ? – Sudhakar Mar 08 '13 at 09:59

1 Answers1

-1

You can use GSON library.

Gson gson = new Gson();

String jsonString = gson.toJson(chartData);

response.setContentType("application/json");

response.getWriter().write(jsonString);
Sagar Gangwal
  • 7,544
  • 3
  • 24
  • 38