2 * $Id: JSONObject.java,v 1.1 2006/04/15 14:10:48 platform Exp $
5 package org.json.simple;
7 import java.io.IOException;
8 import java.io.StringWriter;
10 import java.util.HashMap;
11 import java.util.Iterator;
15 * A JSON object. Key value pairs are unordered. JSONObject supports
16 * java.util.Map interface.
18 * @author FangYidong<fangyidong@yahoo.com.cn>
20 public class JSONObject extends HashMap
21 implements Map, JSONAware, JSONStreamAware
24 private static final long serialVersionUID = -503443796854799292L;
32 * Allows creation of a JSONObject from a Map. After that, both the generated
33 * JSONObject and the Map can be modified independently.
37 public JSONObject(Map map)
43 * Encode a map into JSON text and write it to out. If this map is also a
44 * JSONAware or JSONStreamAware, JSONAware or JSONStreamAware specific
45 * behaviours will be ignored at this top level.
47 * @see org.json.simple.JSONValue#writeJSONString(Object, Writer)
52 public static void writeJSONString(Map map, Writer out) throws IOException
61 Iterator iter = map.entrySet().iterator();
64 while (iter.hasNext())
70 Map.Entry entry = (Map.Entry) iter.next();
72 out.write(escape(String.valueOf(entry.getKey())));
75 JSONValue.writeJSONString(entry.getValue(), out);
80 public void writeJSONString(Writer out) throws IOException
82 writeJSONString(this, out);
86 * Convert a map to JSON text. The result is a JSON object. If this map is
87 * also a JSONAware, JSONAware specific behaviours will be omitted at this top
90 * @see org.json.simple.JSONValue#toJSONString(Object)
93 * @return JSON text, or "null" if map is null.
95 public static String toJSONString(Map map)
97 final StringWriter writer = new StringWriter();
101 writeJSONString(map, writer);
102 return writer.toString();
103 } catch (IOException e)
105 // This should never happen with a StringWriter
106 throw new RuntimeException(e);
110 public String toJSONString()
112 return toJSONString(this);
115 public String toString()
117 return toJSONString();
120 public static String toString(String key, Object value)
122 StringBuffer sb = new StringBuffer();
127 JSONValue.escape(key, sb);
128 sb.append('\"').append(':');
130 sb.append(JSONValue.toJSONString(value));
132 return sb.toString();
136 * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters
137 * (U+0000 through U+001F). It's the same as JSONValue.escape() only for
138 * compatibility here.
140 * @see org.json.simple.JSONValue#escape(String)
145 public static String escape(String s)
147 return JSONValue.escape(s);