I’m starting off with converting some inhouse developed AJAX stuff to using DOJO and for that reason I needed to convert my XML responses to JSON. Using the JSON Java classes this was pretty straight forward but I really needed an easier way to convert a java.util.Map instance to JSON. Extending JSONArray this was easy. Provided here for those who might need similar code…
package org.json; import java.util.Iterator; import java.util.Map; public class JSONMap extends JSONArray { public JSONMap(Map m) { for (Iterator ite=m.keySet().iterator(); ite.hasNext(); ) { String key = (String)ite.next(); String value = m.get(key).toString(); JSONArray a = new JSONArray(); a.put(value); a.put(key); this.put(a); } } }
Code like this
Map m = new HashMap(); m.put("AL", "Alabama"); m.put("AK", "Alaska"); m.put("AR", "Arkansas"); JSONMap jm = new JSONMap(m); System.out.println(jm.toString());
will output the following JSON
[ [ "Alabama", "AL" ], [ "Alaska", "AK" ], [ "Arkansas", "AR" ] ]