01: /*
02: * $Id: JSONObject.java,v 1.1 2006/04/15 14:10:48 platform Exp $
03: * Created on 2006-4-10
04: */
05: package org.zkforge.json.simple;
06:
07: import java.util.HashMap;
08: import java.util.Iterator;
09: import java.util.Map;
10:
11: /**
12: * @author FangYidong<fangyidong@yahoo.com.cn>
13: */
14: public class JSONObject extends HashMap {
15:
16: public String toString() {
17: ItemList list = new ItemList();
18: Iterator iter = entrySet().iterator();
19:
20: while (iter.hasNext()) {
21: Map.Entry entry = (Map.Entry) iter.next();
22: list.add(toString(entry.getKey().toString(), entry
23: .getValue()));
24: }
25: return "{" + list.toString() + "}";
26: }
27:
28: public static String toString(String key, Object value) {
29: StringBuffer sb = new StringBuffer();
30:
31: sb.append("\"");
32: sb.append(escape(key));
33: sb.append("\":");
34: if (value == null) {
35: sb.append("null");
36: return sb.toString();
37: }
38:
39: if (value instanceof String) {
40: sb.append("\"");
41: sb.append(escape((String) value));
42: sb.append("\"");
43: } else
44: sb.append(value);
45: return sb.toString();
46: }
47:
48: /**
49: * " => \" , \ => \\
50: * @param s
51: * @return
52: */
53: public static String escape(String s) {
54: if (s == null)
55: return null;
56: StringBuffer sb = new StringBuffer();
57: for (int i = 0; i < s.length(); i++) {
58: char ch = s.charAt(i);
59: switch (ch) {
60: case '"':
61: sb.append("\\\"");
62: break;
63: case '\\':
64: sb.append("\\\\");
65: break;
66: case '\b':
67: sb.append("\\b");
68: break;
69: case '\f':
70: sb.append("\\f");
71: break;
72: case '\n':
73: sb.append("\\n");
74: break;
75: case '\r':
76: sb.append("\\r");
77: break;
78: case '\t':
79: sb.append("\\t");
80: break;
81: case '/':
82: sb.append("\\/");
83: break;
84: default:
85: if (ch >= '\u0000' && ch <= '\u001F') {
86: String ss = Integer.toHexString(ch);
87: sb.append("\\u");
88: for (int k = 0; k < 4 - ss.length(); k++) {
89: sb.append('0');
90: }
91: sb.append(ss.toUpperCase());
92: } else {
93: sb.append(ch);
94: }
95: }
96: }//for
97: return sb.toString();
98: }
99: }
|