0

In PHP, we return the JSON to an AJAX call like this:

json_encode($data);

How do we do that in JSP?

JSP:

<%      
    gson.toJson(map, System.out);  // last line
%>

jQuery:

$.get("lookup_all_phone_numbers.jsp")
    .done(function(data){
        $("#results").append(data);
    });
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
  • I wouldn't bother with a JSP file but instead have your controller send the JSON directly to the client. What framework are you using (SPring, Struts, etc)? – nickdos Jan 15 '14 at 05:21
  • I am not using any framework. – Rahul Desai Jan 15 '14 at 05:23
  • Just write the JSON out via the HttpServletResponse object. You'll need to use a library to convert the Map to JSON first (see http://stackoverflow.com/q/13340138/249327). – nickdos Jan 15 '14 at 05:47
  • Can you please elaborate? Sorry, I am new to Java/JSP. – Rahul Desai Jan 15 '14 at 05:57
  • You do not need to use JSP to return JSON format. I see, lot of people uses JSP for html representation. If you want JSON, then you can return directly from code instead of JSP rendering. – Fizer Khan Jan 15 '14 at 06:59

1 Answers1

0

I ended up using:

out.print(gson.toJson(map));
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138