1 package org.opensrf.util;
11 /** Special OpenSRF serializable object netClass key */
12 public static final String JSON_CLASS_KEY = "__c";
14 /** Special OpenSRF serializable object payload key */
15 public static final String JSON_PAYLOAD_KEY = "__p";
19 * @see toJSON(Object, StringBuffer)
21 public static String toJSON(Object obj) {
22 StringBuffer sb = new StringBuffer();
29 * Encodes a java object to JSON.
30 * Maps (HashMaps, etc.) are encoded as JSON objects.
31 * Iterable's (Lists, etc.) are encoded as JSON arrays
33 public static void toJSON(Object obj, StringBuffer sb) {
42 if(obj instanceof String) {
44 Utils.escape((String) obj, sb);
50 if(obj instanceof Number) {
51 sb.append(obj.toString());
56 if(obj instanceof Iterable) {
57 encodeJSONArray((Iterable) obj, sb);
61 /** OpenSRF serializable objects */
62 if(obj instanceof OSRFSerializable) {
63 encodeOSRFSerializable((OSRFSerializable) obj, sb);
68 if(obj instanceof Map) {
69 encodeJSONObject((Map) obj, sb);
74 if(obj instanceof Boolean) {
75 sb.append((((Boolean) obj).booleanValue() ? "true" : "false"));
82 * Encodes a List as a JSON array
84 private static void encodeJSONArray(Iterable iterable, StringBuffer sb) {
85 Iterator itr = iterable.iterator();
89 while(itr.hasNext()) {
91 toJSON(itr.next(), sb);
95 /* remove the trailing comma if the array has any items*/
97 sb.deleteCharAt(sb.length()-1);
103 * Encodes a Map to a JSON object
105 private static void encodeJSONObject(Map map, StringBuffer sb) {
106 Iterator itr = map.keySet().iterator();
110 while(itr.hasNext()) {
114 toJSON(map.get(key), sb);
118 /* remove the trailing comma if the object has any items*/
120 sb.deleteCharAt(sb.length()-1);
126 * Encodes a network-serializable OpenSRF object
128 private static void encodeOSRFSerializable(OSRFSerializable obj, StringBuffer sb) {
130 OSRFRegistry reg = obj.getRegistry();
131 String[] fields = reg.getFields();
132 Map<String, Object> map = new HashMap<String, Object>();
133 map.put(JSON_CLASS_KEY, reg.getNetClass());
135 if( reg.getWireProtocol() == OSRFRegistry.WireProtocol.ARRAY ) {
137 List<Object> list = new ArrayList<Object>(fields.length);
138 for(String s : fields)
139 list.add(obj.get(s));
140 map.put(JSON_PAYLOAD_KEY, list);
143 //map.put(JSON_PAYLOAD_KEY, new HashMap<String, Object>(obj));
144 Map<String, Object> subMap = new HashMap<String, Object>();
145 for(String s : fields)
146 map.put(s, obj.get(s));
150 /** now serialize the encoded object */