Posts Tagged ‘json’

Simple Example of Java JSON Encoding in Servlet

May 17th, 2013

Here is a simple example showing how to output json in a servlet. I’ll use the “JSON-java” package which is recommended by and can be downloaded at To encode Java objects into a JSON string, we simply use org.json.JSONObject and

import org.json.JSONArray;
import org.json.JSONObject;

 * A simple example of showing how to output json in a Servlet.
@WebServlet(description = "Test servlet showing how to output json in Java", urlPatterns = { "/services/testjson" })
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Cache-Control", "nocache");
		PrintWriter out = response.getWriter();

		JSONObject json = new JSONObject();

		// put some value pairs into the JSON object as into a Map.
		json.put("status", 200);
		json.put("msg", "OK");

		// put a "map" 
		JSONObject map = new JSONObject();
		map.put("key1", "val1");
		map.put("key2", "val2");
		json.put("map", map);
		// put an "array"
		JSONArray arr = new JSONArray();
		json.put("arr", arr);

		// finally output the json string		

There is another package called json-simple which is also very handy and simple. More information about json-simple can be found at

loop through json object

July 2nd, 2010

p = {k1: v1, k2, v2, k3, v3};
for (var key in p) {
if (p.hasOwnProperty(key)) { // make sure that the key you get is an actual property of an object, and doesn’t come from the prototype: