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 java.util.Map interface.
17 * @author FangYidong<fangyidong@yahoo.com.cn>
19 public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware{
21 private static final long serialVersionUID = -503443796854799292L;
29 * Allows creation of a JSONObject from a Map. After that, both the
30 * generated JSONObject and the Map can be modified independently.
34 public JSONObject(Map map) {
40 * Encode a map into JSON text and write it to out.
41 * If this map is also a JSONAware or JSONStreamAware, JSONAware or JSONStreamAware specific behaviours will be ignored at this top level.
43 * @see org.json.simple.JSONValue#writeJSONString(Object, Writer)
48 public static void writeJSONString(Map map, Writer out) throws IOException {
55 Iterator iter=map.entrySet().iterator();
58 while(iter.hasNext()){
63 Map.Entry entry=(Map.Entry)iter.next();
65 out.write(escape(String.valueOf(entry.getKey())));
68 JSONValue.writeJSONString(entry.getValue(), out);
73 public void writeJSONString(Writer out) throws IOException{
74 writeJSONString(this, out);
78 * Convert a map to JSON text. The result is a JSON object.
79 * If this map is also a JSONAware, JSONAware specific behaviours will be omitted at this top level.
81 * @see org.json.simple.JSONValue#toJSONString(Object)
84 * @return JSON text, or "null" if map is null.
86 public static String toJSONString(Map map){
87 final StringWriter writer = new StringWriter();
90 writeJSONString(map, writer);
91 return writer.toString();
92 } catch (IOException e) {
93 // This should never happen with a StringWriter
94 throw new RuntimeException(e);
98 public String toJSONString(){
99 return toJSONString(this);
102 public String toString(){
103 return toJSONString();
106 public static String toString(String key,Object value){
107 StringBuffer sb = new StringBuffer();
112 JSONValue.escape(key, sb);
113 sb.append('\"').append(':');
115 sb.append(JSONValue.toJSONString(value));
117 return sb.toString();
121 * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
122 * It's the same as JSONValue.escape() only for compatibility here.
124 * @see org.json.simple.JSONValue#escape(String)
129 public static String escape(String s){
130 return JSONValue.escape(s);