try {
Writer outWriter = new BufferedWriter(new OutputStreamWriter(os));
outWriter.flush();
JSON obj = (JSON)toJSONObject(o);
obj.write(outWriter);
outWriter.flush();
} catch (Exception e) {
try {
// how to handle?
os.write(("Couldn't write json because of " + e.toString()).getBytes());
e.printStackTrace();
} catch (IOException ioe) {
}
}
}
public Object toJSONObject(Object obj) {
if (obj instanceof Map) {
Map m = (Map) obj;
JSONObject json = new JSONObject();
Iterator it = m.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
json.put((String) entry.getKey(), toJSONObject(entry.getValue()));
}
return json;
} else if (obj instanceof Collection) {
Collection col = (Collection) obj;
JSONArray json = new JSONArray();
Iterator it = col.iterator();
while (it.hasNext()) {
json.add(toJSONObject(it.next()));
}
return json;
} else if (obj instanceof Number) {
return obj;
} else if (obj == null) {
return JSONNull.getInstance();
} else {
return obj.toString();
}
}
};
}