views:

2039

answers:

6

How do you return a JSON object form a Java servlet.

Previously when doing AJAX with a servlet I have returned a string. Is there a JSON object type that needs to be used, or do you just return a String that looks like a JSON object e.g.

String objectToReturn = "{ key1 = value1, key2 = value2 }";
+2  A: 

I do exactly what you suggest (return a String).

You might consider setting the MIME type to indicate you're returning JSON, though (according to this other stackoverflow post it's "application/json").

Mark E
+2  A: 

Just write a string to the output stream. You might set the MIME-type to text/javascript (edit: application/json is apparently officialer) if you're feeling helpful. (There's a small but nonzero chance that it'll keep something from messing it up someday, and it's a good practice.)

fennec
+1  A: 

There might be a JSON object for java coding convenience. But at last the data structure will be serialized to string. setting a proper MIME type would be nice.

I'd suggest JSON Java from json.org.

nil
A: 

response.setContentType("text/javascript");

//create the JSON string, I suggest using some framework.

String your_string;

out.write(your_string.getBytes("UTF-8"));

do I need to use getBytes("UTF-8")) or can I just return the String variable?
Ankur
It's a safe programming practice to use UTF-8 for encoding the response of a web application.
+1  A: 

Using the response object in the servlet set the contenttype as follows, which will specifys what you are returning.
response.setContentType("application/json"); Get the printwriter object from response to write the required json object to the output stream
PrintWriter out = response.getWriter(); Assume your json object is jsonObject, perform the following, it will return your json object
out.print(jsonObject); out.flush();

A: 

Use Google Gson. It really eases converting (collections/maps of) Java objects to JSON strings so that you don't need to hassle to get the JSON syntax right. I've posted several examples before:

BalusC