Java, JSON

Returning a JSON object from a Java Servlet

The only important thing to keep in mind while returning a JSON object from a Java servlet is to specify the correct MIME type for JSON. The correct MIME type for JSON is application/json.

Therefore, while returning a JSON object from a servlet you need to set the content type like this:

       response.setContentType("application/json");

For your convenience I am attaching a sample code.

	public void doGet(
			HttpServletRequest request,
			HttpServletResponse response
	) {
		
		try {
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			out.println("{");
			out.println("\"First Name\": \"Devesh\",");
			out.println("\"Last Name\": \"Sharma\"");
			out.println("}");
            out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
Advertisements

4 thoughts on “Returning a JSON object from a Java Servlet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s