GRAILS-1019: Allowing expressions to be used with the 'disabled' attribute for g...
[grails.git] / src / web / org / codehaus / groovy / grails / web / json / JSONObject.java
blob7d1c5593ed79e81c7f552731a79d427ba15fbc79
1 package org.codehaus.groovy.grails.web.json;
3 /*
4 Copyright (c) 2002 JSON.org
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
16 The Software shall be used for Good, not Evil.
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 SOFTWARE.
27 import java.io.IOException;
28 import java.io.Writer;
29 import java.util.*;
31 /**
32 * A JSONObject is an unordered collection of name/value pairs. Its
33 * external form is a string wrapped in curly braces with colons between the
34 * names and values, and commas between the values and names. The internal form
35 * is an object having <code>get</code> and <code>opt</code> methods for
36 * accessing the values by name, and <code>put</code> methods for adding or
37 * replacing values by name. The values can be any of these types:
38 * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
39 * <code>Number</code>, <code>String</code>, or the <code>JSONObject.NULL</code>
40 * object. A JSONObject constructor can be used to convert an external form
41 * JSON text into an internal form whose values can be retrieved with the
42 * <code>get</code> and <code>opt</code> methods, or to convert values into a
43 * JSON text using the <code>put</code> and <code>toString</code> methods.
44 * A <code>get</code> method returns a value if one can be found, and throws an
45 * exception if one cannot be found. An <code>opt</code> method returns a
46 * default value instead of throwing an exception, and so is useful for
47 * obtaining optional values.
48 * <p/>
49 * The generic <code>get()</code> and <code>opt()</code> methods return an
50 * object, which you can cast or query for type. There are also typed
51 * <code>get</code> and <code>opt</code> methods that do type checking and type
52 * coersion for you.
53 * <p/>
54 * The <code>put</code> methods adds values to an object. For example, <pre>
55 * myString = new JSONObject().put("JSON", "Hello, World!").toString();</pre>
56 * produces the string <code>{"JSON": "Hello, World"}</code>.
57 * <p/>
58 * The texts produced by the <code>toString</code> methods strictly conform to
59 * the JSON sysntax rules.
60 * The constructors are more forgiving in the texts they will accept:
61 * <ul>
62 * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just
63 * before the closing brace.</li>
64 * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single
65 * quote)</small>.</li>
66 * <li>Strings do not need to be quoted at all if they do not begin with a quote
67 * or single quote, and if they do not contain leading or trailing spaces,
68 * and if they do not contain any of these characters:
69 * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
70 * and if they are not the reserved words <code>true</code>,
71 * <code>false</code>, or <code>null</code>.</li>
72 * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as
73 * by <code>:</code>.</li>
74 * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as
75 * well as by <code>,</code> <small>(comma)</small>.</li>
76 * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or
77 * <code>0x-</code> <small>(hex)</small> prefix.</li>
78 * <li>Comments written in the slashshlash, slashstar, and hash conventions
79 * will be ignored.</li>
80 * </ul>
82 * @author JSON.org
83 * @version 2
85 public class JSONObject implements Map {
87 /**
88 * JSONObject.NULL is equivalent to the value that JavaScript calls null,
89 * whilst Java's null is equivalent to the value that JavaScript calls
90 * undefined.
92 private static final class Null {
94 /**
95 * There is only intended to be a single instance of the NULL object,
96 * so the clone method returns itself.
98 * @return NULL.
100 protected final Object clone() {
101 return this;
106 * A Null object is equal to the null value and to itself.
108 * @param object An object to test for nullness.
109 * @return true if the object parameter is the JSONObject.NULL object
110 * or null.
112 public boolean equals(Object object) {
113 return object == null || object == this;
118 * Get the "null" string value.
120 * @return The string "null".
122 public String toString() {
123 return "null";
129 * The hash map where the JSONObject's properties are kept.
131 private HashMap myHashMap;
135 * It is sometimes more convenient and less ambiguous to have a
136 * <code>NULL</code> object than to use Java's <code>null</code> value.
137 * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
138 * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
140 public static final Object NULL = new Null();
144 * Construct an empty JSONObject.
146 public JSONObject() {
147 this.myHashMap = new HashMap();
152 * Construct a JSONObject from a subset of another JSONObject.
153 * An array of strings is used to identify the keys that should be copied.
154 * Missing keys are ignored.
156 * @param jo A JSONObject.
157 * @param sa An array of strings.
158 * @throws JSONException If a value is a non-finite number.
160 public JSONObject(JSONObject jo, String[] sa) throws JSONException {
161 this();
162 for (int i = 0; i < sa.length; i += 1) {
163 putOpt(sa[i], jo.opt(sa[i]));
169 * Construct a JSONObject from a JSONTokener.
171 * @param x A JSONTokener object containing the source string.
172 * @throws JSONException If there is a syntax error in the source string.
174 public JSONObject(JSONTokener x) throws JSONException {
175 this();
176 char c;
177 String key;
179 if (x.nextClean() != '{') {
180 throw x.syntaxError("A JSONObject text must begin with '{'");
182 for (; ;) {
183 c = x.nextClean();
184 switch (c) {
185 case 0:
186 throw x.syntaxError("A JSONObject text must end with '}'");
187 case '}':
188 return;
189 default:
190 x.back();
191 key = x.nextValue().toString();
195 * The key is followed by ':'. We will also tolerate '=' or '=>'.
198 c = x.nextClean();
199 if (c == '=') {
200 if (x.next() != '>') {
201 x.back();
203 } else if (c != ':') {
204 throw x.syntaxError("Expected a ':' after a key");
206 this.myHashMap.put(key, x.nextValue());
209 * Pairs are separated by ','. We will also tolerate ';'.
212 switch (x.nextClean()) {
213 case ';':
214 case ',':
215 if (x.nextClean() == '}') {
216 return;
218 x.back();
219 break;
220 case '}':
221 return;
222 default:
223 throw x.syntaxError("Expected a ',' or '}'");
230 * Construct a JSONObject from a Map.
232 * @param map A map object that can be used to initialize the contents of
233 * the JSONObject.
235 public JSONObject(Map map) {
236 this.myHashMap = new HashMap(map);
241 * Construct a JSONObject from a string.
242 * This is the most commonly used JSONObject constructor.
244 * @param string A string beginning
245 * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
246 * with <code>}</code>&nbsp;<small>(right brace)</small>.
247 * @throws JSONException If there is a syntax error in the source string.
249 public JSONObject(String string) throws JSONException {
250 this(new JSONTokener(string));
255 * Accumulate values under a key. It is similar to the put method except
256 * that if there is already an object stored under the key then a
257 * JSONArray is stored under the key to hold all of the accumulated values.
258 * If there is already a JSONArray, then the new value is appended to it.
259 * In contrast, the put method replaces the previous value.
261 * @param key A key string.
262 * @param value An object to be accumulated under the key.
263 * @return this.
264 * @throws JSONException If the value is an invalid number
265 * or if the key is null.
267 public JSONObject accumulate(String key, Object value)
268 throws JSONException {
269 testValidity(value);
270 Object o = opt(key);
271 if (o == null) {
272 put(key, value);
273 } else if (o instanceof JSONArray) {
274 ((JSONArray) o).put(value);
275 } else {
276 put(key, new JSONArray().put(o).put(value));
278 return this;
283 * Get the value object associated with a key.
285 * @param key A key string.
286 * @return The object associated with the key.
287 * @throws JSONException if the key is not found.
289 public Object get(String key) throws JSONException {
290 Object o = opt(key);
291 if (o == null) {
292 throw new JSONException("JSONObject[" + quote(key) +
293 "] not found.");
295 return o;
300 * Get the boolean value associated with a key.
302 * @param key A key string.
303 * @return The truth.
304 * @throws JSONException if the value is not a Boolean or the String "true" or "false".
306 public boolean getBoolean(String key) throws JSONException {
307 Object o = get(key);
308 if (o.equals(Boolean.FALSE) ||
309 (o instanceof String &&
310 ((String) o).equalsIgnoreCase("false"))) {
311 return false;
312 } else if (o.equals(Boolean.TRUE) ||
313 (o instanceof String &&
314 ((String) o).equalsIgnoreCase("true"))) {
315 return true;
317 throw new JSONException("JSONObject[" + quote(key) +
318 "] is not a Boolean.");
323 * Get the double value associated with a key.
325 * @param key A key string.
326 * @return The numeric value.
327 * @throws JSONException if the key is not found or
328 * if the value is not a Number object and cannot be converted to a number.
330 public double getDouble(String key) throws JSONException {
331 Object o = get(key);
332 try {
333 return o instanceof Number ?
334 ((Number) o).doubleValue() : Double.parseDouble((String) o);
335 } catch (Exception e) {
336 throw new JSONException("JSONObject[" + quote(key) +
337 "] is not a number.");
343 * Get the int value associated with a key. If the number value is too
344 * large for an int, it will be clipped.
346 * @param key A key string.
347 * @return The integer value.
348 * @throws JSONException if the key is not found or if the value cannot
349 * be converted to an integer.
351 public int getInt(String key) throws JSONException {
352 Object o = get(key);
353 return o instanceof Number ?
354 ((Number) o).intValue() : (int) getDouble(key);
359 * Get the JSONArray value associated with a key.
361 * @param key A key string.
362 * @return A JSONArray which is the value.
363 * @throws JSONException if the key is not found or
364 * if the value is not a JSONArray.
366 public JSONArray getJSONArray(String key) throws JSONException {
367 Object o = get(key);
368 if (o instanceof JSONArray) {
369 return (JSONArray) o;
371 throw new JSONException("JSONObject[" + quote(key) +
372 "] is not a JSONArray.");
377 * Get the JSONObject value associated with a key.
379 * @param key A key string.
380 * @return A JSONObject which is the value.
381 * @throws JSONException if the key is not found or
382 * if the value is not a JSONObject.
384 public JSONObject getJSONObject(String key) throws JSONException {
385 Object o = get(key);
386 if (o instanceof JSONObject) {
387 return (JSONObject) o;
389 throw new JSONException("JSONObject[" + quote(key) +
390 "] is not a JSONObject.");
395 * Get the long value associated with a key. If the number value is too
396 * long for a long, it will be clipped.
398 * @param key A key string.
399 * @return The long value.
400 * @throws JSONException if the key is not found or if the value cannot
401 * be converted to a long.
403 public long getLong(String key) throws JSONException {
404 Object o = get(key);
405 return o instanceof Number ?
406 ((Number) o).longValue() : (long) getDouble(key);
411 * Get the string associated with a key.
413 * @param key A key string.
414 * @return A string which is the value.
415 * @throws JSONException if the key is not found.
417 public String getString(String key) throws JSONException {
418 return get(key).toString();
423 * Determine if the JSONObject contains a specific key.
425 * @param key A key string.
426 * @return true if the key exists in the JSONObject.
428 public boolean has(String key) {
429 return this.myHashMap.containsKey(key);
434 * Determine if the value associated with the key is null or if there is
435 * no value.
437 * @param key A key string.
438 * @return true if there is no value associated with the key or if
439 * the value is the JSONObject.NULL object.
441 public boolean isNull(String key) {
442 return JSONObject.NULL.equals(opt(key));
447 * Get an enumeration of the keys of the JSONObject.
449 * @return An iterator of the keys.
451 public Iterator keys() {
452 return this.myHashMap.keySet().iterator();
457 * Get the number of keys stored in the JSONObject.
459 * @return The number of keys in the JSONObject.
461 public int length() {
462 return this.myHashMap.size();
467 * Produce a JSONArray containing the names of the elements of this
468 * JSONObject.
470 * @return A JSONArray containing the key strings, or null if the JSONObject
471 * is empty.
473 public JSONArray names() {
474 JSONArray ja = new JSONArray();
475 Iterator keys = keys();
476 while (keys.hasNext()) {
477 ja.put(keys.next());
479 return ja.length() == 0 ? null : ja;
483 * Produce a string from a number.
485 * @param n A Number
486 * @return A String.
487 * @throws JSONException If n is a non-finite number.
489 static public String numberToString(Number n)
490 throws JSONException {
491 if (n == null) {
492 throw new JSONException("Null pointer");
494 testValidity(n);
496 // Shave off trailing zeros and decimal point, if possible.
498 String s = n.toString();
499 if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
500 while (s.endsWith("0")) {
501 s = s.substring(0, s.length() - 1);
503 if (s.endsWith(".")) {
504 s = s.substring(0, s.length() - 1);
507 return s;
510 static public String dateToString(Date d) throws JSONException {
511 return "new Date(" + d.getTime() + ")";
516 * Get an optional value associated with a key.
518 * @param key A key string.
519 * @return An object which is the value, or null if there is no value.
521 public Object opt(String key) {
522 return key == null ? null : this.myHashMap.get(key);
527 * Get an optional boolean associated with a key.
528 * It returns false if there is no such key, or if the value is not
529 * Boolean.TRUE or the String "true".
531 * @param key A key string.
532 * @return The truth.
534 public boolean optBoolean(String key) {
535 return optBoolean(key, false);
540 * Get an optional boolean associated with a key.
541 * It returns the defaultValue if there is no such key, or if it is not
542 * a Boolean or the String "true" or "false" (case insensitive).
544 * @param key A key string.
545 * @param defaultValue The default.
546 * @return The truth.
548 public boolean optBoolean(String key, boolean defaultValue) {
549 try {
550 return getBoolean(key);
551 } catch (Exception e) {
552 return defaultValue;
558 * Get an optional double associated with a key,
559 * or NaN if there is no such key or if its value is not a number.
560 * If the value is a string, an attempt will be made to evaluate it as
561 * a number.
563 * @param key A string which is the key.
564 * @return An object which is the value.
566 public double optDouble(String key) {
567 return optDouble(key, Double.NaN);
572 * Get an optional double associated with a key, or the
573 * defaultValue if there is no such key or if its value is not a number.
574 * If the value is a string, an attempt will be made to evaluate it as
575 * a number.
577 * @param key A key string.
578 * @param defaultValue The default.
579 * @return An object which is the value.
581 public double optDouble(String key, double defaultValue) {
582 try {
583 Object o = opt(key);
584 return o instanceof Number ? ((Number) o).doubleValue() :
585 new Double((String) o).doubleValue();
586 } catch (Exception e) {
587 return defaultValue;
593 * Get an optional int value associated with a key,
594 * or zero if there is no such key or if the value is not a number.
595 * If the value is a string, an attempt will be made to evaluate it as
596 * a number.
598 * @param key A key string.
599 * @return An object which is the value.
601 public int optInt(String key) {
602 return optInt(key, 0);
607 * Get an optional int value associated with a key,
608 * or the default if there is no such key or if the value is not a number.
609 * If the value is a string, an attempt will be made to evaluate it as
610 * a number.
612 * @param key A key string.
613 * @param defaultValue The default.
614 * @return An object which is the value.
616 public int optInt(String key, int defaultValue) {
617 try {
618 return getInt(key);
619 } catch (Exception e) {
620 return defaultValue;
626 * Get an optional JSONArray associated with a key.
627 * It returns null if there is no such key, or if its value is not a
628 * JSONArray.
630 * @param key A key string.
631 * @return A JSONArray which is the value.
633 public JSONArray optJSONArray(String key) {
634 Object o = opt(key);
635 return o instanceof JSONArray ? (JSONArray) o : null;
640 * Get an optional JSONObject associated with a key.
641 * It returns null if there is no such key, or if its value is not a
642 * JSONObject.
644 * @param key A key string.
645 * @return A JSONObject which is the value.
647 public JSONObject optJSONObject(String key) {
648 Object o = opt(key);
649 return o instanceof JSONObject ? (JSONObject) o : null;
654 * Get an optional long value associated with a key,
655 * or zero if there is no such key or if the value is not a number.
656 * If the value is a string, an attempt will be made to evaluate it as
657 * a number.
659 * @param key A key string.
660 * @return An object which is the value.
662 public long optLong(String key) {
663 return optLong(key, 0);
668 * Get an optional long value associated with a key,
669 * or the default if there is no such key or if the value is not a number.
670 * If the value is a string, an attempt will be made to evaluate it as
671 * a number.
673 * @param key A key string.
674 * @param defaultValue The default.
675 * @return An object which is the value.
677 public long optLong(String key, long defaultValue) {
678 try {
679 return getLong(key);
680 } catch (Exception e) {
681 return defaultValue;
687 * Get an optional string associated with a key.
688 * It returns an empty string if there is no such key. If the value is not
689 * a string and is not null, then it is coverted to a string.
691 * @param key A key string.
692 * @return A string which is the value.
694 public String optString(String key) {
695 return optString(key, "");
700 * Get an optional string associated with a key.
701 * It returns the defaultValue if there is no such key.
703 * @param key A key string.
704 * @param defaultValue The default.
705 * @return A string which is the value.
707 public String optString(String key, String defaultValue) {
708 Object o = opt(key);
709 return o != null ? o.toString() : defaultValue;
714 * Put a key/boolean pair in the JSONObject.
716 * @param key A key string.
717 * @param value A boolean which is the value.
718 * @return this.
719 * @throws JSONException If the key is null.
721 public JSONObject put(String key, boolean value) throws JSONException {
722 put(key, value ? Boolean.TRUE : Boolean.FALSE);
723 return this;
728 * Put a key/double pair in the JSONObject.
730 * @param key A key string.
731 * @param value A double which is the value.
732 * @return this.
733 * @throws JSONException If the key is null or if the number is invalid.
735 public JSONObject put(String key, double value) throws JSONException {
736 put(key, new Double(value));
737 return this;
742 * Put a key/int pair in the JSONObject.
744 * @param key A key string.
745 * @param value An int which is the value.
746 * @return this.
747 * @throws JSONException If the key is null.
749 public JSONObject put(String key, int value) throws JSONException {
750 put(key, new Integer(value));
751 return this;
756 * Put a key/long pair in the JSONObject.
758 * @param key A key string.
759 * @param value A long which is the value.
760 * @return this.
761 * @throws JSONException If the key is null.
763 public JSONObject put(String key, long value) throws JSONException {
764 put(key, new Long(value));
765 return this;
770 * Put a key/value pair in the JSONObject. If the value is null,
771 * then the key will be removed from the JSONObject if it is present.
773 * @param key A key string.
774 * @param value An object which is the value. It should be of one of these
775 * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
776 * or the JSONObject.NULL object.
777 * @return this.
778 * @throws JSONException If the value is non-finite number
779 * or if the key is null.
781 public JSONObject put(String key, Object value) throws JSONException {
782 if (key == null) {
783 throw new JSONException("Null key.");
785 if (value != null) {
786 testValidity(value);
787 this.myHashMap.put(key, value);
788 } else {
789 remove(key);
791 return this;
796 * Put a key/value pair in the JSONObject, but only if the
797 * key and the value are both non-null.
799 * @param key A key string.
800 * @param value An object which is the value. It should be of one of these
801 * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
802 * or the JSONObject.NULL object.
803 * @return this.
804 * @throws JSONException If the value is a non-finite number.
806 public JSONObject putOpt(String key, Object value) throws JSONException {
807 if (key != null && value != null) {
808 put(key, value);
810 return this;
815 * Produce a string in double quotes with backslash sequences in all the
816 * right places. A backslash will be inserted within </, allowing JSON
817 * text to be delivered in HTML. In JSON text, a string cannot contain a
818 * control character or an unescaped quote or backslash.
820 * @param string A String
821 * @return A String correctly formatted for insertion in a JSON text.
823 public static String quote(String string) {
824 if (string == null || string.length() == 0) {
825 return "\"\"";
828 char b;
829 char c = 0;
830 int i;
831 int len = string.length();
832 StringBuffer sb = new StringBuffer(len + 4);
833 String t;
835 sb.append('"');
836 for (i = 0; i < len; i += 1) {
837 b = c;
838 c = string.charAt(i);
839 switch (c) {
840 case '\\':
841 case '"':
842 sb.append('\\');
843 sb.append(c);
844 break;
845 case '/':
846 if (b == '<') {
847 sb.append('\\');
849 sb.append(c);
850 break;
851 case '\b':
852 sb.append("\\b");
853 break;
854 case '\t':
855 sb.append("\\t");
856 break;
857 case '\n':
858 sb.append("\\n");
859 break;
860 case '\f':
861 sb.append("\\f");
862 break;
863 case '\r':
864 sb.append("\\r");
865 break;
866 default:
867 if (c < ' ') {
868 t = "000" + Integer.toHexString(c);
869 sb.append("\\u" + t.substring(t.length() - 4));
870 } else {
871 sb.append(c);
875 sb.append('"');
876 return sb.toString();
880 * Remove a name and its value, if present.
882 * @param key The name to be removed.
883 * @return The value that was associated with the name,
884 * or null if there was no value.
886 public Object remove(String key) {
887 return this.myHashMap.remove(key);
891 * Throw an exception if the object is an NaN or infinite number.
893 * @param o The object to test.
894 * @throws JSONException If o is a non-finite number.
896 static void testValidity(Object o) throws JSONException {
897 if (o != null) {
898 if (o instanceof Double) {
899 if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
900 throw new JSONException(
901 "JSON does not allow non-finite numbers");
903 } else if (o instanceof Float) {
904 if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
905 throw new JSONException(
906 "JSON does not allow non-finite numbers.");
914 * Produce a JSONArray containing the values of the members of this
915 * JSONObject.
917 * @param names A JSONArray containing a list of key strings. This
918 * determines the sequence of the values in the result.
919 * @return A JSONArray of values.
920 * @throws JSONException If any of the values are non-finite numbers.
922 public JSONArray toJSONArray(JSONArray names) throws JSONException {
923 if (names == null || names.length() == 0) {
924 return null;
926 JSONArray ja = new JSONArray();
927 for (int i = 0; i < names.length(); i += 1) {
928 ja.put(this.opt(names.getString(i)));
930 return ja;
934 * Make an JSON text of this JSONObject. For compactness, no whitespace
935 * is added. If this would not result in a syntactically correct JSON text,
936 * then null will be returned instead.
937 * <p/>
938 * Warning: This method assumes that the data structure is acyclical.
940 * @return a printable, displayable, portable, transmittable
941 * representation of the object, beginning
942 * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
943 * with <code>}</code>&nbsp;<small>(right brace)</small>.
945 public String toString() {
946 try {
947 Iterator keys = keys();
948 StringBuffer sb = new StringBuffer("{");
950 while (keys.hasNext()) {
951 if (sb.length() > 1) {
952 sb.append(',');
954 Object o = keys.next();
955 sb.append(quote(o.toString()));
956 sb.append(':');
957 sb.append(valueToString(this.myHashMap.get(o)));
959 sb.append('}');
960 return sb.toString();
961 } catch (Exception e) {
962 return null;
968 * Make a prettyprinted JSON text of this JSONObject.
969 * <p/>
970 * Warning: This method assumes that the data structure is acyclical.
972 * @param indentFactor The number of spaces to add to each level of
973 * indentation.
974 * @return a printable, displayable, portable, transmittable
975 * representation of the object, beginning
976 * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
977 * with <code>}</code>&nbsp;<small>(right brace)</small>.
978 * @throws JSONException If the object contains an invalid number.
980 public String toString(int indentFactor) throws JSONException {
981 return toString(indentFactor, 0);
986 * Make a prettyprinted JSON text of this JSONObject.
987 * <p/>
988 * Warning: This method assumes that the data structure is acyclical.
990 * @param indentFactor The number of spaces to add to each level of
991 * indentation.
992 * @param indent The indentation of the top level.
993 * @return a printable, displayable, transmittable
994 * representation of the object, beginning
995 * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
996 * with <code>}</code>&nbsp;<small>(right brace)</small>.
997 * @throws JSONException If the object contains an invalid number.
999 String toString(int indentFactor, int indent) throws JSONException {
1000 int i;
1001 int n = length();
1002 if (n == 0) {
1003 return "{}";
1005 Iterator keys = keys();
1006 StringBuffer sb = new StringBuffer("{");
1007 int newindent = indent + indentFactor;
1008 Object o;
1009 if (n == 1) {
1010 o = keys.next();
1011 sb.append(quote(o.toString()));
1012 sb.append(": ");
1013 sb.append(valueToString(this.myHashMap.get(o), indentFactor,
1014 indent));
1015 } else {
1016 while (keys.hasNext()) {
1017 o = keys.next();
1018 if (sb.length() > 1) {
1019 sb.append(",\n");
1020 } else {
1021 sb.append('\n');
1023 for (i = 0; i < newindent; i += 1) {
1024 sb.append(' ');
1026 sb.append(quote(o.toString()));
1027 sb.append(": ");
1028 sb.append(valueToString(this.myHashMap.get(o), indentFactor,
1029 newindent));
1031 if (sb.length() > 1) {
1032 sb.append('\n');
1033 for (i = 0; i < indent; i += 1) {
1034 sb.append(' ');
1038 sb.append('}');
1039 return sb.toString();
1044 * Make a JSON text of an object value.
1045 * <p/>
1046 * Warning: This method assumes that the data structure is acyclical.
1048 * @param value The value to be serialized.
1049 * @return a printable, displayable, transmittable
1050 * representation of the object, beginning
1051 * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
1052 * with <code>}</code>&nbsp;<small>(right brace)</small>.
1053 * @throws JSONException If the value is or contains an invalid number.
1055 static String valueToString(Object value) throws JSONException {
1056 if (value == null || value.equals(null)) {
1057 return "null";
1059 if (value instanceof Number) {
1060 return numberToString((Number) value);
1062 if (value instanceof Date) {
1063 return dateToString((Date) value);
1065 if (value instanceof Boolean || value instanceof JSONObject ||
1066 value instanceof JSONArray) {
1067 return value.toString();
1069 return quote(value.toString());
1074 * Make a prettyprinted JSON text of an object value.
1075 * <p/>
1076 * Warning: This method assumes that the data structure is acyclical.
1078 * @param value The value to be serialized.
1079 * @param indentFactor The number of spaces to add to each level of
1080 * indentation.
1081 * @param indent The indentation of the top level.
1082 * @return a printable, displayable, transmittable
1083 * representation of the object, beginning
1084 * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
1085 * with <code>}</code>&nbsp;<small>(right brace)</small>.
1086 * @throws JSONException If the object contains an invalid number.
1088 static String valueToString(Object value, int indentFactor, int indent)
1089 throws JSONException {
1090 if (value == null || value.equals(null)) {
1091 return "null";
1093 if (value instanceof Number) {
1094 return numberToString((Number) value);
1096 if (value instanceof Date) {
1097 return dateToString((Date) value);
1099 if (value instanceof Boolean) {
1100 return value.toString();
1102 if (value instanceof JSONObject) {
1103 return ((JSONObject) value).toString(indentFactor, indent);
1105 if (value instanceof JSONArray) {
1106 return ((JSONArray) value).toString(indentFactor, indent);
1108 return quote(value.toString());
1113 * Write the contents of the JSONObject as JSON text to a writer.
1114 * For compactness, no whitespace is added.
1115 * <p/>
1116 * Warning: This method assumes that the data structure is acyclical.
1118 * @return The writer.
1119 * @throws JSONException
1121 public Writer write(Writer writer) throws JSONException {
1122 try {
1123 boolean b = false;
1124 Iterator keys = keys();
1125 writer.write('{');
1127 while (keys.hasNext()) {
1128 if (b) {
1129 writer.write(',');
1131 Object k = keys.next();
1132 writer.write(quote(k.toString()));
1133 writer.write(':');
1134 Object v = this.myHashMap.get(k);
1135 if (v instanceof JSONObject) {
1136 ((JSONObject) v).write(writer);
1137 } else if (v instanceof JSONArray) {
1138 ((JSONArray) v).write(writer);
1139 } else {
1140 writer.write(valueToString(v));
1142 b = true;
1144 writer.write('}');
1145 return writer;
1146 } catch (IOException e) {
1147 throw new JSONException(e);
1151 public int size() {
1152 return this.myHashMap.size();
1155 public boolean isEmpty() {
1156 return this.myHashMap.isEmpty();
1159 public boolean containsKey(Object o) {
1160 return false;
1163 public boolean containsValue(Object o) {
1164 return this.myHashMap.containsKey(o);
1167 public Object get(Object o) {
1168 return this.myHashMap.get(o);
1171 public Object put(Object o, Object o1) {
1172 return this.myHashMap.put(o, o1);
1175 public Object remove(Object o) {
1176 return this.myHashMap.remove(o);
1179 public void putAll(Map map) {
1180 this.myHashMap.putAll(map);
1183 public void clear() {
1184 this.myHashMap.clear();
1187 public Set keySet() {
1188 return this.myHashMap.keySet();
1191 public Collection values() {
1192 return this.myHashMap.values();
1195 public Set entrySet() {
1196 return this.myHashMap.entrySet();
1199 public boolean equals(Object o) {
1200 if (this == o) return true;
1201 if (o == null || getClass() != o.getClass()) return false;
1203 JSONObject that = (JSONObject) o;
1205 if (myHashMap != null ? !myHashMap.equals(that.myHashMap) : that.myHashMap != null) return false;
1207 return true;
1210 public int hashCode() {
1211 return (myHashMap != null ? myHashMap.hashCode() : 0);
1214 // public Object asType(Class targetClass) {
1215 // if(ConverterUtil.isDomainClass(targetClass)) {
1217 // }
1218 // }