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 http://json.org/java/ and can be downloaded at https://github.com/douglascrockford/JSON-java. To encode Java objects into a JSON string, we simply use org.json.JSONObject and org.json.JSONArray.java.

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.setContentType("application/json");
		response.setHeader("Cache-Control", "nocache");
        	response.setCharacterEncoding("utf-8");
		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();
		arr.put(5);
		arr.put(3);
		arr.put(1);
		json.put("arr", arr);

		// finally output the json string		
		out.print(json.toString());
	}
}

There is another package called json-simple which is also very handy and simple. More information about json-simple can be found at https://code.google.com/p/json-simple/.

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:
alert(p[key]);
}
}