rafayali
11/21/2014 - 10:46 AM

Sending JSON data to Client from Servlet

/**
	 * Sends data back to client by using HTTPServletResponse object and adding data into JSON Array 
	 * then flushes out the stream and closes the response
	 * Sends data
	 * @param resp
	 * @param result
	 * @param message
	 * @param stringData
	 * @throws IOException
	 */
	public static void sendData(HttpServletResponse resp, String result, String message, List<String> stringData) throws IOException {
		JSONArray data = new JSONArray();
		data.put(result);
		data.put(message);
		
		if(stringData != null)
			for(String s : stringData){
				data.put(s);
			}

		final String output = data.toString();
		resp.setContentLength(output.length());
		resp.getOutputStream().write(output.getBytes());
		resp.getOutputStream().flush();
		resp.getOutputStream().close();
	}