1 package org.opensrf.util;
11 public static final String JSON_CLASS_KEY = "__c";
12 public static final String JSON_PAYLOAD_KEY = "__p";
16 * @see toJSON(Object, StringBuffer)
18 public static String toJSON(Object obj) {
19 StringBuffer sb = new StringBuffer();
26 * Encodes a java object to JSON.
27 * Maps (HashMaps, etc.) are encoded as JSON objects.
28 * Iterable's (Lists, etc.) are encoded as JSON arrays
30 public static void toJSON(Object obj, StringBuffer sb) {
39 if(obj instanceof String) {
41 Utils.escape((String) obj, sb);
47 if(obj instanceof Number) {
48 sb.append(obj.toString());
53 if(obj instanceof Iterable) {
54 encodeJSONArray((Iterable) obj, sb);
59 if(obj instanceof Map) {
60 encodeJSONObject((Map) obj, sb);
65 if(obj instanceof Boolean) {
66 sb.append((((Boolean) obj).booleanValue() ? "true" : "false"));
73 * Encodes a List as a JSON array
75 private static void encodeJSONArray(Iterable iterable, StringBuffer sb) {
76 Iterator itr = iterable.iterator();
80 while(itr.hasNext()) {
82 toJSON(itr.next(), sb);
86 /* remove the trailing comma if the array has any items*/
88 sb.deleteCharAt(sb.length()-1);
94 * Encodes a Map to a JSON object
96 private static void encodeJSONObject(Map map, StringBuffer sb) {
97 Iterator itr = map.keySet().iterator();
101 while(itr.hasNext()) {
105 toJSON(map.get(key), sb);
109 /* remove the trailing comma if the object has any items*/
111 sb.deleteCharAt(sb.length()-1);