PageRenderTime 57ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/src/org/json/JSONObject.java

http://github.com/nddrylliog/ooc
Java | 1575 lines | 911 code | 132 blank | 532 comment | 121 complexity | 94b1ecd8fe8f8fd2be5cae09338ecc0b MD5 | raw file
  1. package org.json;
  2. /*
  3. Copyright (c) 2002 JSON.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. The Software shall be used for Good, not Evil.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. SOFTWARE.
  20. */
  21. import java.io.IOException;
  22. import java.io.Writer;
  23. import java.lang.reflect.Field;
  24. import java.lang.reflect.Method;
  25. import java.lang.reflect.Modifier;
  26. import java.util.Collection;
  27. import java.util.HashMap;
  28. import java.util.Iterator;
  29. import java.util.Map;
  30. import java.util.TreeSet;
  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. * coercion 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 syntax 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. * </ul>
  79. * @author JSON.org
  80. * @version 2009-03-06
  81. */
  82. public class JSONObject {
  83. /**
  84. * JSONObject.NULL is equivalent to the value that JavaScript calls null,
  85. * whilst Java's null is equivalent to the value that JavaScript calls
  86. * undefined.
  87. */
  88. static final class Null {
  89. /**
  90. * There is only intended to be a single instance of the NULL object,
  91. * so the clone method returns itself.
  92. * @return NULL.
  93. */
  94. @Override
  95. protected final Object clone() {
  96. return this;
  97. }
  98. /**
  99. * A Null object is equal to the null value and to itself.
  100. * @param object An object to test for nullness.
  101. * @return true if the object parameter is the JSONObject.NULL object
  102. * or null.
  103. */
  104. @Override
  105. public boolean equals(Object object) {
  106. return object == null || object == this;
  107. }
  108. /**
  109. * Get the "null" string value.
  110. * @return The string "null".
  111. */
  112. @Override
  113. public String toString() {
  114. return "null";
  115. }
  116. }
  117. /**
  118. * The map where the JSONObject's properties are kept.
  119. */
  120. private Map<Object, Object> map;
  121. /**
  122. * It is sometimes more convenient and less ambiguous to have a
  123. * <code>NULL</code> object than to use Java's <code>null</code> value.
  124. * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
  125. * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
  126. */
  127. public static final Object NULL = new Null();
  128. /**
  129. * Construct an empty JSONObject.
  130. */
  131. public JSONObject() {
  132. this.map = new HashMap<Object, Object>();
  133. }
  134. /**
  135. * Construct a JSONObject from a subset of another JSONObject.
  136. * An array of strings is used to identify the keys that should be copied.
  137. * Missing keys are ignored.
  138. * @param jo A JSONObject.
  139. * @param names An array of strings.
  140. * @exception JSONException If a value is a non-finite number or if a name is duplicated.
  141. */
  142. public JSONObject(JSONObject jo, String[] names) throws JSONException {
  143. this();
  144. for (int i = 0; i < names.length; i += 1) {
  145. putOnce(names[i], jo.opt(names[i]));
  146. }
  147. }
  148. /**
  149. * Construct a JSONObject from a JSONTokener.
  150. * @param x A JSONTokener object containing the source string.
  151. * @throws JSONException If there is a syntax error in the source string
  152. * or a duplicated key.
  153. */
  154. public JSONObject(JSONTokener x) throws JSONException {
  155. this();
  156. char c;
  157. String key;
  158. if (x.nextClean() != '{') {
  159. throw x.syntaxError("A JSONObject text must begin with '{'");
  160. }
  161. for (;;) {
  162. c = x.nextClean();
  163. switch (c) {
  164. case 0:
  165. throw x.syntaxError("A JSONObject text must end with '}'");
  166. case '}':
  167. return;
  168. default:
  169. x.back();
  170. key = x.nextValue().toString();
  171. }
  172. /*
  173. * The key is followed by ':'. We will also tolerate '=' or '=>'.
  174. */
  175. c = x.nextClean();
  176. if (c == '=') {
  177. if (x.next() != '>') {
  178. x.back();
  179. }
  180. } else if (c != ':') {
  181. throw x.syntaxError("Expected a ':' after a key");
  182. }
  183. putOnce(key, x.nextValue());
  184. /*
  185. * Pairs are separated by ','. We will also tolerate ';'.
  186. */
  187. switch (x.nextClean()) {
  188. case ';':
  189. case ',':
  190. if (x.nextClean() == '}') {
  191. return;
  192. }
  193. x.back();
  194. break;
  195. case '}':
  196. return;
  197. default:
  198. throw x.syntaxError("Expected a ',' or '}'");
  199. }
  200. }
  201. }
  202. /**
  203. * Construct a JSONObject from a Map.
  204. *
  205. * @param map A map object that can be used to initialize the contents of
  206. * the JSONObject.
  207. */
  208. public JSONObject(Map<Object, Object> map) {
  209. this.map = (map == null) ? new HashMap<Object, Object>() : map;
  210. }
  211. /**
  212. * Construct a JSONObject from a Map.
  213. *
  214. * Note: Use this constructor when the map contains <key,bean>.
  215. *
  216. * @param map - A map with Key-Bean data.
  217. * @param includeSuperClass - Tell whether to include the super class properties.
  218. */
  219. public JSONObject(Map<?, ?> map, boolean includeSuperClass) {
  220. this.map = new HashMap<Object, Object>();
  221. if (map != null) {
  222. Iterator<?> i = map.entrySet().iterator();
  223. while (i.hasNext()) {
  224. Map.Entry<?, ?> e = (Map.Entry<?, ?>) i.next();
  225. if (isStandardProperty(e.getValue().getClass())) {
  226. this.map.put(e.getKey(), e.getValue());
  227. } else {
  228. this.map.put(e.getKey(), new JSONObject(e.getValue(),
  229. includeSuperClass));
  230. }
  231. }
  232. }
  233. }
  234. /**
  235. * Construct a JSONObject from an Object using bean getters.
  236. * It reflects on all of the public methods of the object.
  237. * For each of the methods with no parameters and a name starting
  238. * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter,
  239. * the method is invoked, and a key and the value returned from the getter method
  240. * are put into the new JSONObject.
  241. *
  242. * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix.
  243. * If the second remaining character is not upper case, then the first
  244. * character is converted to lower case.
  245. *
  246. * For example, if an object has a method named <code>"getName"</code>, and
  247. * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>,
  248. * then the JSONObject will contain <code>"name": "Larry Fine"</code>.
  249. *
  250. * @param bean An object that has getter methods that should be used
  251. * to make a JSONObject.
  252. */
  253. public JSONObject(Object bean) {
  254. this();
  255. populateInternalMap(bean, false);
  256. }
  257. /**
  258. * Construct a JSONObject from an Object using bean getters.
  259. * It reflects on all of the public methods of the object.
  260. * For each of the methods with no parameters and a name starting
  261. * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter,
  262. * the method is invoked, and a key and the value returned from the getter method
  263. * are put into the new JSONObject.
  264. *
  265. * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix.
  266. * If the second remaining character is not upper case, then the first
  267. * character is converted to lower case.
  268. *
  269. * @param bean An object that has getter methods that should be used
  270. * to make a JSONObject.
  271. * @param includeSuperClass If true, include the super class properties.
  272. */
  273. public JSONObject(Object bean, boolean includeSuperClass) {
  274. this();
  275. populateInternalMap(bean, includeSuperClass);
  276. }
  277. @SuppressWarnings("cast")
  278. private void populateInternalMap(Object bean, boolean includeSuperClassParam){
  279. boolean includeSuperClass = includeSuperClassParam;
  280. Class<?> klass = bean.getClass();
  281. /* If klass.getSuperClass is System class then force includeSuperClass to false. */
  282. if (klass.getClassLoader() == null) {
  283. includeSuperClass = false;
  284. }
  285. Method[] methods = (includeSuperClass) ?
  286. klass.getMethods() : klass.getDeclaredMethods();
  287. for (int i = 0; i < methods.length; i += 1) {
  288. try {
  289. Method method = methods[i];
  290. if (Modifier.isPublic(method.getModifiers())) {
  291. String name = method.getName();
  292. String key = "";
  293. if (name.startsWith("get")) {
  294. key = name.substring(3);
  295. } else if (name.startsWith("is")) {
  296. key = name.substring(2);
  297. }
  298. if (key.length() > 0 &&
  299. Character.isUpperCase(key.charAt(0)) &&
  300. method.getParameterTypes().length == 0) {
  301. if (key.length() == 1) {
  302. key = key.toLowerCase();
  303. } else if (!Character.isUpperCase(key.charAt(1))) {
  304. key = key.substring(0, 1).toLowerCase() +
  305. key.substring(1);
  306. }
  307. Object result = method.invoke(bean, (Object[])null);
  308. if (result == null) {
  309. map.put(key, NULL);
  310. } else if (result.getClass().isArray()) {
  311. map.put(key, new JSONArray(result, includeSuperClass));
  312. } else if (result instanceof Collection<?>) { // List or Set
  313. map.put(key, new JSONArray((Collection<?>) result, includeSuperClass));
  314. } else if (result instanceof Map<?, ?>) {
  315. map.put(key, new JSONObject((Map<?, ?>)result, includeSuperClass));
  316. } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper
  317. map.put(key, result);
  318. } else {
  319. if (result.getClass().getPackage().getName().startsWith("java") ||
  320. result.getClass().getClassLoader() == null) {
  321. map.put(key, result.toString());
  322. } else { // User defined Objects
  323. map.put(key, new JSONObject(result, includeSuperClass));
  324. }
  325. }
  326. }
  327. }
  328. } catch (Exception e) {
  329. throw new RuntimeException(e);
  330. }
  331. }
  332. }
  333. static boolean isStandardProperty(Class<?> clazz) {
  334. return clazz.isPrimitive() ||
  335. clazz.isAssignableFrom(Byte.class) ||
  336. clazz.isAssignableFrom(Short.class) ||
  337. clazz.isAssignableFrom(Integer.class) ||
  338. clazz.isAssignableFrom(Long.class) ||
  339. clazz.isAssignableFrom(Float.class) ||
  340. clazz.isAssignableFrom(Double.class) ||
  341. clazz.isAssignableFrom(Character.class) ||
  342. clazz.isAssignableFrom(String.class) ||
  343. clazz.isAssignableFrom(Boolean.class);
  344. }
  345. /**
  346. * Construct a JSONObject from an Object, using reflection to find the
  347. * public members. The resulting JSONObject's keys will be the strings
  348. * from the names array, and the values will be the field values associated
  349. * with those keys in the object. If a key is not found or not visible,
  350. * then it will not be copied into the new JSONObject.
  351. * @param object An object that has fields that should be used to make a
  352. * JSONObject.
  353. * @param names An array of strings, the names of the fields to be obtained
  354. * from the object.
  355. */
  356. public JSONObject(Object object, String names[]) {
  357. this();
  358. Class<?> c = object.getClass();
  359. for (int i = 0; i < names.length; i += 1) {
  360. String name = names[i];
  361. try {
  362. putOpt(name, c.getField(name).get(object));
  363. } catch (Exception e) {
  364. /* forget about it */
  365. }
  366. }
  367. }
  368. /**
  369. * Construct a JSONObject from a source JSON text string.
  370. * This is the most commonly used JSONObject constructor.
  371. * @param source A string beginning
  372. * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  373. * with <code>}</code>&nbsp;<small>(right brace)</small>.
  374. * @exception JSONException If there is a syntax error in the source
  375. * string or a duplicated key.
  376. */
  377. public JSONObject(String source) throws JSONException {
  378. this(new JSONTokener(source));
  379. }
  380. /**
  381. * Accumulate values under a key. It is similar to the put method except
  382. * that if there is already an object stored under the key then a
  383. * JSONArray is stored under the key to hold all of the accumulated values.
  384. * If there is already a JSONArray, then the new value is appended to it.
  385. * In contrast, the put method replaces the previous value.
  386. * @param key A key string.
  387. * @param value An object to be accumulated under the key.
  388. * @return this.
  389. * @throws JSONException If the value is an invalid number
  390. * or if the key is null.
  391. */
  392. public JSONObject accumulate(String key, Object value)
  393. throws JSONException {
  394. testValidity(value);
  395. Object o = opt(key);
  396. if (o == null) {
  397. put(key, value instanceof JSONArray ?
  398. new JSONArray().put(value) :
  399. value);
  400. } else if (o instanceof JSONArray) {
  401. ((JSONArray)o).put(value);
  402. } else {
  403. put(key, new JSONArray().put(o).put(value));
  404. }
  405. return this;
  406. }
  407. /**
  408. * Append values to the array under a key. If the key does not exist in the
  409. * JSONObject, then the key is put in the JSONObject with its value being a
  410. * JSONArray containing the value parameter. If the key was already
  411. * associated with a JSONArray, then the value parameter is appended to it.
  412. * @param key A key string.
  413. * @param value An object to be accumulated under the key.
  414. * @return this.
  415. * @throws JSONException If the key is null or if the current value
  416. * associated with the key is not a JSONArray.
  417. */
  418. public JSONObject append(String key, Object value)
  419. throws JSONException {
  420. testValidity(value);
  421. Object o = opt(key);
  422. if (o == null) {
  423. put(key, new JSONArray().put(value));
  424. } else if (o instanceof JSONArray) {
  425. put(key, ((JSONArray)o).put(value));
  426. } else {
  427. throw new JSONException("JSONObject[" + key +
  428. "] is not a JSONArray.");
  429. }
  430. return this;
  431. }
  432. /**
  433. * Produce a string from a double. The string "null" will be returned if
  434. * the number is not finite.
  435. * @param d A double.
  436. * @return A String.
  437. */
  438. static public String doubleToString(double d) {
  439. if (Double.isInfinite(d) || Double.isNaN(d)) {
  440. return "null";
  441. }
  442. // Shave off trailing zeros and decimal point, if possible.
  443. String s = Double.toString(d);
  444. if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
  445. while (s.endsWith("0")) {
  446. s = s.substring(0, s.length() - 1);
  447. }
  448. if (s.endsWith(".")) {
  449. s = s.substring(0, s.length() - 1);
  450. }
  451. }
  452. return s;
  453. }
  454. /**
  455. * Get the value object associated with a key.
  456. *
  457. * @param key A key string.
  458. * @return The object associated with the key.
  459. * @throws JSONException if the key is not found.
  460. */
  461. public Object get(String key) throws JSONException {
  462. Object o = opt(key);
  463. if (o == null) {
  464. throw new JSONException("JSONObject[" + quote(key) +
  465. "] not found.");
  466. }
  467. return o;
  468. }
  469. /**
  470. * Get the boolean value associated with a key.
  471. *
  472. * @param key A key string.
  473. * @return The truth.
  474. * @throws JSONException
  475. * if the value is not a Boolean or the String "true" or "false".
  476. */
  477. public boolean getBoolean(String key) throws JSONException {
  478. Object o = get(key);
  479. if (o.equals(Boolean.FALSE) ||
  480. (o instanceof String &&
  481. ((String)o).equalsIgnoreCase("false"))) {
  482. return false;
  483. } else if (o.equals(Boolean.TRUE) ||
  484. (o instanceof String &&
  485. ((String)o).equalsIgnoreCase("true"))) {
  486. return true;
  487. }
  488. throw new JSONException("JSONObject[" + quote(key) +
  489. "] is not a Boolean.");
  490. }
  491. /**
  492. * Get the double value associated with a key.
  493. * @param key A key string.
  494. * @return The numeric value.
  495. * @throws JSONException if the key is not found or
  496. * if the value is not a Number object and cannot be converted to a number.
  497. */
  498. public double getDouble(String key) throws JSONException {
  499. Object o = get(key);
  500. try {
  501. return o instanceof Number ?
  502. ((Number)o).doubleValue() :
  503. Double.valueOf((String)o).doubleValue();
  504. } catch (Exception e) {
  505. throw new JSONException("JSONObject[" + quote(key) +
  506. "] is not a number.");
  507. }
  508. }
  509. /**
  510. * Get the int value associated with a key. If the number value is too
  511. * large for an int, it will be clipped.
  512. *
  513. * @param key A key string.
  514. * @return The integer value.
  515. * @throws JSONException if the key is not found or if the value cannot
  516. * be converted to an integer.
  517. */
  518. public int getInt(String key) throws JSONException {
  519. Object o = get(key);
  520. return o instanceof Number ?
  521. ((Number)o).intValue() : (int)getDouble(key);
  522. }
  523. /**
  524. * Get the JSONArray value associated with a key.
  525. *
  526. * @param key A key string.
  527. * @return A JSONArray which is the value.
  528. * @throws JSONException if the key is not found or
  529. * if the value is not a JSONArray.
  530. */
  531. public JSONArray getJSONArray(String key) throws JSONException {
  532. Object o = get(key);
  533. if (o instanceof JSONArray) {
  534. return (JSONArray)o;
  535. }
  536. throw new JSONException("JSONObject[" + quote(key) +
  537. "] is not a JSONArray.");
  538. }
  539. /**
  540. * Get the JSONObject value associated with a key.
  541. *
  542. * @param key A key string.
  543. * @return A JSONObject which is the value.
  544. * @throws JSONException if the key is not found or
  545. * if the value is not a JSONObject.
  546. */
  547. public JSONObject getJSONObject(String key) throws JSONException {
  548. Object o = get(key);
  549. if (o instanceof JSONObject) {
  550. return (JSONObject)o;
  551. }
  552. throw new JSONException("JSONObject[" + quote(key) +
  553. "] is not a JSONObject.");
  554. }
  555. /**
  556. * Get the long value associated with a key. If the number value is too
  557. * long for a long, it will be clipped.
  558. *
  559. * @param key A key string.
  560. * @return The long value.
  561. * @throws JSONException if the key is not found or if the value cannot
  562. * be converted to a long.
  563. */
  564. public long getLong(String key) throws JSONException {
  565. Object o = get(key);
  566. return o instanceof Number ?
  567. ((Number)o).longValue() : (long)getDouble(key);
  568. }
  569. /**
  570. * Get an array of field names from a JSONObject.
  571. *
  572. * @return An array of field names, or null if there are no names.
  573. */
  574. public static String[] getNames(JSONObject jo) {
  575. int length = jo.length();
  576. if (length == 0) {
  577. return null;
  578. }
  579. Iterator<?> i = jo.keys();
  580. String[] names = new String[length];
  581. int j = 0;
  582. while (i.hasNext()) {
  583. names[j] = (String)i.next();
  584. j += 1;
  585. }
  586. return names;
  587. }
  588. /**
  589. * Get an array of field names from an Object.
  590. *
  591. * @return An array of field names, or null if there are no names.
  592. */
  593. public static String[] getNames(Object object) {
  594. if (object == null) {
  595. return null;
  596. }
  597. Class<?> klass = object.getClass();
  598. Field[] fields = klass.getFields();
  599. int length = fields.length;
  600. if (length == 0) {
  601. return null;
  602. }
  603. String[] names = new String[length];
  604. for (int i = 0; i < length; i += 1) {
  605. names[i] = fields[i].getName();
  606. }
  607. return names;
  608. }
  609. /**
  610. * Get the string associated with a key.
  611. *
  612. * @param key A key string.
  613. * @return A string which is the value.
  614. * @throws JSONException if the key is not found.
  615. */
  616. public String getString(String key) throws JSONException {
  617. return get(key).toString();
  618. }
  619. /**
  620. * Determine if the JSONObject contains a specific key.
  621. * @param key A key string.
  622. * @return true if the key exists in the JSONObject.
  623. */
  624. public boolean has(String key) {
  625. return this.map.containsKey(key);
  626. }
  627. /**
  628. * Determine if the value associated with the key is null or if there is
  629. * no value.
  630. * @param key A key string.
  631. * @return true if there is no value associated with the key or if
  632. * the value is the JSONObject.NULL object.
  633. */
  634. public boolean isNull(String key) {
  635. return JSONObject.NULL.equals(opt(key));
  636. }
  637. /**
  638. * Get an enumeration of the keys of the JSONObject.
  639. *
  640. * @return An iterator of the keys.
  641. */
  642. public Iterator<?> keys() {
  643. return this.map.keySet().iterator();
  644. }
  645. /**
  646. * Get the number of keys stored in the JSONObject.
  647. *
  648. * @return The number of keys in the JSONObject.
  649. */
  650. public int length() {
  651. return this.map.size();
  652. }
  653. /**
  654. * Produce a JSONArray containing the names of the elements of this
  655. * JSONObject.
  656. * @return A JSONArray containing the key strings, or null if the JSONObject
  657. * is empty.
  658. */
  659. public JSONArray names() {
  660. JSONArray ja = new JSONArray();
  661. Iterator<?> keys = keys();
  662. while (keys.hasNext()) {
  663. ja.put(keys.next());
  664. }
  665. return ja.length() == 0 ? null : ja;
  666. }
  667. /**
  668. * Produce a string from a Number.
  669. * @param n A Number
  670. * @return A String.
  671. * @throws JSONException If n is a non-finite number.
  672. */
  673. static public String numberToString(Number n)
  674. throws JSONException {
  675. if (n == null) {
  676. throw new JSONException("Null pointer");
  677. }
  678. testValidity(n);
  679. // Shave off trailing zeros and decimal point, if possible.
  680. String s = n.toString();
  681. if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
  682. while (s.endsWith("0")) {
  683. s = s.substring(0, s.length() - 1);
  684. }
  685. if (s.endsWith(".")) {
  686. s = s.substring(0, s.length() - 1);
  687. }
  688. }
  689. return s;
  690. }
  691. /**
  692. * Get an optional value associated with a key.
  693. * @param key A key string.
  694. * @return An object which is the value, or null if there is no value.
  695. */
  696. public Object opt(String key) {
  697. return key == null ? null : this.map.get(key);
  698. }
  699. /**
  700. * Get an optional boolean associated with a key.
  701. * It returns false if there is no such key, or if the value is not
  702. * Boolean.TRUE or the String "true".
  703. *
  704. * @param key A key string.
  705. * @return The truth.
  706. */
  707. public boolean optBoolean(String key) {
  708. return optBoolean(key, false);
  709. }
  710. /**
  711. * Get an optional boolean associated with a key.
  712. * It returns the defaultValue if there is no such key, or if it is not
  713. * a Boolean or the String "true" or "false" (case insensitive).
  714. *
  715. * @param key A key string.
  716. * @param defaultValue The default.
  717. * @return The truth.
  718. */
  719. public boolean optBoolean(String key, boolean defaultValue) {
  720. try {
  721. return getBoolean(key);
  722. } catch (Exception e) {
  723. return defaultValue;
  724. }
  725. }
  726. /**
  727. * Put a key/value pair in the JSONObject, where the value will be a
  728. * JSONArray which is produced from a Collection.
  729. * @param key A key string.
  730. * @param value A Collection value.
  731. * @return this.
  732. * @throws JSONException
  733. */
  734. public JSONObject put(String key, Collection<Object> value) throws JSONException {
  735. put(key, new JSONArray(value));
  736. return this;
  737. }
  738. /**
  739. * Get an optional double associated with a key,
  740. * or NaN if there is no such key or if its value is not a number.
  741. * If the value is a string, an attempt will be made to evaluate it as
  742. * a number.
  743. *
  744. * @param key A string which is the key.
  745. * @return An object which is the value.
  746. */
  747. public double optDouble(String key) {
  748. return optDouble(key, Double.NaN);
  749. }
  750. /**
  751. * Get an optional double associated with a key, or the
  752. * defaultValue if there is no such key or if its value is not a number.
  753. * If the value is a string, an attempt will be made to evaluate it as
  754. * a number.
  755. *
  756. * @param key A key string.
  757. * @param defaultValue The default.
  758. * @return An object which is the value.
  759. */
  760. public double optDouble(String key, double defaultValue) {
  761. try {
  762. Object o = opt(key);
  763. return o instanceof Number ? ((Number)o).doubleValue() :
  764. new Double((String)o).doubleValue();
  765. } catch (Exception e) {
  766. return defaultValue;
  767. }
  768. }
  769. /**
  770. * Get an optional int value associated with a key,
  771. * or zero if there is no such key or if the value is not a number.
  772. * If the value is a string, an attempt will be made to evaluate it as
  773. * a number.
  774. *
  775. * @param key A key string.
  776. * @return An object which is the value.
  777. */
  778. public int optInt(String key) {
  779. return optInt(key, 0);
  780. }
  781. /**
  782. * Get an optional int value associated with a key,
  783. * or the default if there is no such key or if the value is not a number.
  784. * If the value is a string, an attempt will be made to evaluate it as
  785. * a number.
  786. *
  787. * @param key A key string.
  788. * @param defaultValue The default.
  789. * @return An object which is the value.
  790. */
  791. public int optInt(String key, int defaultValue) {
  792. try {
  793. return getInt(key);
  794. } catch (Exception e) {
  795. return defaultValue;
  796. }
  797. }
  798. /**
  799. * Get an optional JSONArray associated with a key.
  800. * It returns null if there is no such key, or if its value is not a
  801. * JSONArray.
  802. *
  803. * @param key A key string.
  804. * @return A JSONArray which is the value.
  805. */
  806. public JSONArray optJSONArray(String key) {
  807. Object o = opt(key);
  808. return o instanceof JSONArray ? (JSONArray)o : null;
  809. }
  810. /**
  811. * Get an optional JSONObject associated with a key.
  812. * It returns null if there is no such key, or if its value is not a
  813. * JSONObject.
  814. *
  815. * @param key A key string.
  816. * @return A JSONObject which is the value.
  817. */
  818. public JSONObject optJSONObject(String key) {
  819. Object o = opt(key);
  820. return o instanceof JSONObject ? (JSONObject)o : null;
  821. }
  822. /**
  823. * Get an optional long value associated with a key,
  824. * or zero if there is no such key or if the value is not a number.
  825. * If the value is a string, an attempt will be made to evaluate it as
  826. * a number.
  827. *
  828. * @param key A key string.
  829. * @return An object which is the value.
  830. */
  831. public long optLong(String key) {
  832. return optLong(key, 0);
  833. }
  834. /**
  835. * Get an optional long value associated with a key,
  836. * or the default if there is no such key or if the value is not a number.
  837. * If the value is a string, an attempt will be made to evaluate it as
  838. * a number.
  839. *
  840. * @param key A key string.
  841. * @param defaultValue The default.
  842. * @return An object which is the value.
  843. */
  844. public long optLong(String key, long defaultValue) {
  845. try {
  846. return getLong(key);
  847. } catch (Exception e) {
  848. return defaultValue;
  849. }
  850. }
  851. /**
  852. * Get an optional string associated with a key.
  853. * It returns an empty string if there is no such key. If the value is not
  854. * a string and is not null, then it is coverted to a string.
  855. *
  856. * @param key A key string.
  857. * @return A string which is the value.
  858. */
  859. public String optString(String key) {
  860. return optString(key, "");
  861. }
  862. /**
  863. * Get an optional string associated with a key.
  864. * It returns the defaultValue if there is no such key.
  865. *
  866. * @param key A key string.
  867. * @param defaultValue The default.
  868. * @return A string which is the value.
  869. */
  870. public String optString(String key, String defaultValue) {
  871. Object o = opt(key);
  872. return o != null ? o.toString() : defaultValue;
  873. }
  874. /**
  875. * Put a key/boolean pair in the JSONObject.
  876. *
  877. * @param key A key string.
  878. * @param value A boolean which is the value.
  879. * @return this.
  880. * @throws JSONException If the key is null.
  881. */
  882. public JSONObject put(String key, boolean value) throws JSONException {
  883. put(key, value ? Boolean.TRUE : Boolean.FALSE);
  884. return this;
  885. }
  886. /**
  887. * Put a key/double pair in the JSONObject.
  888. *
  889. * @param key A key string.
  890. * @param value A double which is the value.
  891. * @return this.
  892. * @throws JSONException If the key is null or if the number is invalid.
  893. */
  894. public JSONObject put(String key, double value) throws JSONException {
  895. put(key, new Double(value));
  896. return this;
  897. }
  898. /**
  899. * Put a key/int pair in the JSONObject.
  900. *
  901. * @param key A key string.
  902. * @param value An int which is the value.
  903. * @return this.
  904. * @throws JSONException If the key is null.
  905. */
  906. public JSONObject put(String key, int value) throws JSONException {
  907. put(key, new Integer(value));
  908. return this;
  909. }
  910. /**
  911. * Put a key/long pair in the JSONObject.
  912. *
  913. * @param key A key string.
  914. * @param value A long which is the value.
  915. * @return this.
  916. * @throws JSONException If the key is null.
  917. */
  918. public JSONObject put(String key, long value) throws JSONException {
  919. put(key, new Long(value));
  920. return this;
  921. }
  922. /**
  923. * Put a key/value pair in the JSONObject, where the value will be a
  924. * JSONObject which is produced from a Map.
  925. * @param key A key string.
  926. * @param value A Map value.
  927. * @return this.
  928. * @throws JSONException
  929. */
  930. public JSONObject put(String key, Map<?, ?> value) throws JSONException {
  931. put(key, new JSONObject(value));
  932. return this;
  933. }
  934. /**
  935. * Put a key/value pair in the JSONObject. If the value is null,
  936. * then the key will be removed from the JSONObject if it is present.
  937. * @param key A key string.
  938. * @param value An object which is the value. It should be of one of these
  939. * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
  940. * or the JSONObject.NULL object.
  941. * @return this.
  942. * @throws JSONException If the value is non-finite number
  943. * or if the key is null.
  944. */
  945. public JSONObject put(String key, Object value) throws JSONException {
  946. if (key == null) {
  947. throw new JSONException("Null key.");
  948. }
  949. if (value != null) {
  950. testValidity(value);
  951. this.map.put(key, value);
  952. } else {
  953. remove(key);
  954. }
  955. return this;
  956. }
  957. /**
  958. * Put a key/value pair in the JSONObject, but only if the key and the
  959. * value are both non-null, and only if there is not already a member
  960. * with that name.
  961. * @param key
  962. * @param value
  963. * @return his.
  964. * @throws JSONException if the key is a duplicate
  965. */
  966. public JSONObject putOnce(String key, Object value) throws JSONException {
  967. if (key != null && value != null) {
  968. if (opt(key) != null) {
  969. throw new JSONException("Duplicate key \"" + key + "\"");
  970. }
  971. put(key, value);
  972. }
  973. return this;
  974. }
  975. /**
  976. * Put a key/value pair in the JSONObject, but only if the
  977. * key and the value are both non-null.
  978. * @param key A key string.
  979. * @param value An object which is the value. It should be of one of these
  980. * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
  981. * or the JSONObject.NULL object.
  982. * @return this.
  983. * @throws JSONException If the value is a non-finite number.
  984. */
  985. public JSONObject putOpt(String key, Object value) throws JSONException {
  986. if (key != null && value != null) {
  987. put(key, value);
  988. }
  989. return this;
  990. }
  991. /**
  992. * Produce a string in double quotes with backslash sequences in all the
  993. * right places. A backslash will be inserted within </, allowing JSON
  994. * text to be delivered in HTML. In JSON text, a string cannot contain a
  995. * control character or an unescaped quote or backslash.
  996. * @param string A String
  997. * @return A String correctly formatted for insertion in a JSON text.
  998. */
  999. public static String quote(String string) {
  1000. if (string == null || string.length() == 0) {
  1001. return "\"\"";
  1002. }
  1003. char b;
  1004. char c = 0;
  1005. int i;
  1006. int len = string.length();
  1007. StringBuffer sb = new StringBuffer(len + 4);
  1008. String t;
  1009. sb.append('"');
  1010. for (i = 0; i < len; i += 1) {
  1011. b = c;
  1012. c = string.charAt(i);
  1013. switch (c) {
  1014. case '\\':
  1015. case '"':
  1016. sb.append('\\');
  1017. sb.append(c);
  1018. break;
  1019. case '/':
  1020. if (b == '<') {
  1021. sb.append('\\');
  1022. }
  1023. sb.append(c);
  1024. break;
  1025. case '\b':
  1026. sb.append("\\b");
  1027. break;
  1028. case '\t':
  1029. sb.append("\\t");
  1030. break;
  1031. case '\n':
  1032. sb.append("\\n");
  1033. break;
  1034. case '\f':
  1035. sb.append("\\f");
  1036. break;
  1037. case '\r':
  1038. sb.append("\\r");
  1039. break;
  1040. default:
  1041. if (c < ' ' || (c >= '\u0080' && c < '\u00a0') ||
  1042. (c >= '\u2000' && c < '\u2100')) {
  1043. t = "000" + Integer.toHexString(c);
  1044. sb.append("\\u" + t.substring(t.length() - 4));
  1045. } else {
  1046. sb.append(c);
  1047. }
  1048. }
  1049. }
  1050. sb.append('"');
  1051. return sb.toString();
  1052. }
  1053. /**
  1054. * Remove a name and its value, if present.
  1055. * @param key The name to be removed.
  1056. * @return The value that was associated with the name,
  1057. * or null if there was no value.
  1058. */
  1059. public Object remove(String key) {
  1060. return this.map.remove(key);
  1061. }
  1062. /**
  1063. * Get an enumeration of the keys of the JSONObject.
  1064. * The keys will be sorted alphabetically.
  1065. *
  1066. * @return An iterator of the keys.
  1067. */
  1068. public Iterator<?> sortedKeys() {
  1069. return new TreeSet<Object>(this.map.keySet()).iterator();
  1070. }
  1071. /**
  1072. * Try to convert a string into a number, boolean, or null. If the string
  1073. * can't be converted, return the string.
  1074. * @param s A String.
  1075. * @return A simple JSON value.
  1076. */
  1077. static public Object stringToValue(String s) {
  1078. if (s.equals("")) {
  1079. return s;
  1080. }
  1081. if (s.equalsIgnoreCase("true")) {
  1082. return Boolean.TRUE;
  1083. }
  1084. if (s.equalsIgnoreCase("false")) {
  1085. return Boolean.FALSE;
  1086. }
  1087. if (s.equalsIgnoreCase("null")) {
  1088. return JSONObject.NULL;
  1089. }
  1090. /*
  1091. * If it might be a number, try converting it. We support the 0- and 0x-
  1092. * conventions. If a number cannot be produced, then the value will just
  1093. * be a string. Note that the 0-, 0x-, plus, and implied string
  1094. * conventions are non-standard. A JSON parser is free to accept
  1095. * non-JSON forms as long as it accepts all correct JSON forms.
  1096. */
  1097. char b = s.charAt(0);
  1098. if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
  1099. if (b == '0') {
  1100. if (s.length() > 2 &&
  1101. (s.charAt(1) == 'x' || s.charAt(1) == 'X')) {
  1102. try {
  1103. return new Integer(Integer.parseInt(s.substring(2),
  1104. 16));
  1105. } catch (Exception e) {
  1106. /* Ignore the error */
  1107. }
  1108. } else {
  1109. try {
  1110. return new Integer(Integer.parseInt(s, 8));
  1111. } catch (Exception e) {
  1112. /* Ignore the error */
  1113. }
  1114. }
  1115. }
  1116. try {
  1117. if (s.indexOf('.') > -1 || s.indexOf('e') > -1 || s.indexOf('E') > -1) {
  1118. return Double.valueOf(s);
  1119. }
  1120. Long myLong = new Long(s);
  1121. if (myLong.longValue() == myLong.intValue()) {
  1122. return new Integer(myLong.intValue());
  1123. }
  1124. return myLong;
  1125. } catch (Exception f) {
  1126. /* Ignore the error */
  1127. }
  1128. }
  1129. return s;
  1130. }
  1131. /**
  1132. * Throw an exception if the object is an NaN or infinite number.
  1133. * @param o The object to test.
  1134. * @throws JSONException If o is a non-finite number.
  1135. */
  1136. static void testValidity(Object o) throws JSONException {
  1137. if (o != null) {
  1138. if (o instanceof Double) {
  1139. if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
  1140. throw new JSONException(
  1141. "JSON does not allow non-finite numbers.");
  1142. }
  1143. } else if (o instanceof Float) {
  1144. if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
  1145. throw new JSONException(
  1146. "JSON does not allow non-finite numbers.");
  1147. }
  1148. }
  1149. }
  1150. }
  1151. /**
  1152. * Produce a JSONArray containing the values of the members of this
  1153. * JSONObject.
  1154. * @param names A JSONArray containing a list of key strings. This
  1155. * determines the sequence of the values in the result.
  1156. * @return A JSONArray of values.
  1157. * @throws JSONException If any of the values are non-finite numbers.
  1158. */
  1159. public JSONArray toJSONArray(JSONArray names) throws JSONException {
  1160. if (names == null || names.length() == 0) {
  1161. return null;
  1162. }
  1163. JSONArray ja = new JSONArray();
  1164. for (int i = 0; i < names.length(); i += 1) {
  1165. ja.put(this.opt(names.getString(i)));
  1166. }
  1167. return ja;
  1168. }
  1169. /**
  1170. * Make a JSON text of this JSONObject. For compactness, no whitespace
  1171. * is added. If this would not result in a syntactically correct JSON text,
  1172. * then null will be returned instead.
  1173. * <p>
  1174. * Warning: This method assumes that the data structure is acyclical.
  1175. *
  1176. * @return a printable, displayable, portable, transmittable
  1177. * representation of the object, beginning
  1178. * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  1179. * with <code>}</code>&nbsp;<small>(right brace)</small>.
  1180. */
  1181. @Override
  1182. public String toString() {
  1183. try {
  1184. Iterator<?> keys = keys();
  1185. StringBuffer sb = new StringBuffer("{");
  1186. while (keys.hasNext()) {
  1187. if (sb.length() > 1) {
  1188. sb.append(',');
  1189. }
  1190. Object o = keys.next();
  1191. sb.append(quote(o.toString()));
  1192. sb.append(':');
  1193. sb.append(valueToString(this.map.get(o)));
  1194. }
  1195. sb.append('}');
  1196. return sb.toString();
  1197. } catch (Exception e) {
  1198. return null;
  1199. }
  1200. }
  1201. /**
  1202. * Make a prettyprinted JSON text of this JSONObject.
  1203. * <p>
  1204. * Warning: This method assumes that the data structure is acyclical.
  1205. * @param indentFactor The number of spaces to add to each level of
  1206. * indentation.
  1207. * @return a printable, displayable, portable, transmittable
  1208. * representation of the object, beginning
  1209. * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  1210. * with <code>}</code>&nbsp;<small>(right brace)</small>.
  1211. * @throws JSONException If the object contains an invalid number.
  1212. */
  1213. public String toString(int indentFactor) throws JSONException {
  1214. return toString(indentFactor, 0);
  1215. }
  1216. /**
  1217. * Make a prettyprinted JSON text of this JSONObject.
  1218. * <p>
  1219. * Warning: This method assumes that the data structure is acyclical.
  1220. * @param indentFactor The number of spaces to add to each level of
  1221. * indentation.
  1222. * @param indent The indentation of the top level.
  1223. * @return a printable, displayable, transmittable
  1224. * representation of the object, beginning
  1225. * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  1226. * with <code>}</code>&nbsp;<small>(right brace)</small>.
  1227. * @throws JSONException If the object contains an invalid number.
  1228. */
  1229. String toString(int indentFactor, int indent) throws JSONException {
  1230. int j;
  1231. int n = length();
  1232. if (n == 0) {
  1233. return "{}";
  1234. }
  1235. Iterator<?> keys = sortedKeys();
  1236. StringBuffer sb = new StringBuffer("{");
  1237. int newindent = indent + indentFactor;
  1238. Object o;
  1239. if (n == 1) {
  1240. o = keys.next();
  1241. sb.append(quote(o.toString()));
  1242. sb.append(": ");
  1243. sb.append(valueToString(this.map.get(o), indentFactor,
  1244. indent));
  1245. } else {
  1246. while (keys.hasNext()) {
  1247. o = keys.next();
  1248. if (sb.length() > 1) {
  1249. sb.append(",\n");
  1250. } else {
  1251. sb.append('\n');
  1252. }
  1253. for (j = 0; j < newindent; j += 1) {
  1254. sb.append(' ');
  1255. }
  1256. sb.append(quote(o.toString()));
  1257. sb.append(": ");
  1258. sb.append(valueToString(this.map.get(o), indentFactor,
  1259. newindent));
  1260. }
  1261. if (sb.length() > 1) {
  1262. sb.append('\n');
  1263. for (j = 0; j < indent; j += 1) {
  1264. sb.append(' ');
  1265. }
  1266. }
  1267. }
  1268. sb.append('}');
  1269. return sb.toString();
  1270. }
  1271. /**
  1272. * Make a JSON text of an Object value. If the object has an
  1273. * value.toJSONString() method, then that method will be used to produce
  1274. * the JSON text. The method is required to produce a strictly
  1275. * conforming text. If the object does not contain a toJSONString
  1276. * method (which is the most common case), then a text will be
  1277. * produced by other means. If the value is an array or Collection,
  1278. * then a JSONArray will be made from it and its toJSONString method
  1279. * will be called. If the value is a MAP, then a JSONObject will be made
  1280. * from it and its toJSONString method will be called. Otherwise, the
  1281. * value's toString method will be called, and the result will be quoted.
  1282. *
  1283. * <p>
  1284. * Warning: This method assumes that the data structure is acyclical.
  1285. * @param value The value to be serialized.
  1286. * @return a printable, displayable, transmittable
  1287. * representation of the object, beginning
  1288. * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  1289. * with <code>}</code>&nbsp;<small>(right brace)</small>.
  1290. * @throws JSONException If the value is or contains an invalid number.
  1291. */
  1292. @SuppressWarnings("cast")
  1293. static String valueToString(Object value) throws JSONException {
  1294. if (value == null || value.equals(null)) {
  1295. return "null";
  1296. }
  1297. if (value instanceof JSONString) {
  1298. Object o;
  1299. try {
  1300. o = ((JSONString)value).toJSONString();
  1301. } catch (Exception e) {
  1302. throw new JSONException(e);
  1303. }
  1304. if (o instanceof String) {
  1305. return (String)o;
  1306. }
  1307. throw new JSONException("Bad value from toJSONString: " + o);
  1308. }
  1309. if (value instanceof Number) {
  1310. return numberToString((Number) value);
  1311. }
  1312. if (value instanceof Boolean || value instanceof JSONObject ||
  1313. value instanceof JSONArray) {
  1314. return value.toString();
  1315. }
  1316. if (value instanceof Map<?, ?>) {
  1317. return new JSONObject((Map<?, ?>)value).toString();
  1318. }
  1319. if (value instanceof Collection<?>) {
  1320. return new JSONArray((Collection<?>) value).toString();
  1321. }
  1322. if (value.getClass().isArray()) {
  1323. return new JSONArray(value).toString();
  1324. }
  1325. return quote(value.toString());
  1326. }
  1327. /**
  1328. * Make a prettyprinted JSON text of an object value.
  1329. * <p>
  1330. * Warning: This method assumes that the data structure is acyclical.
  1331. * @param value The value to be serialized.
  1332. * @param indentFactor The number of spaces to add to each level of
  1333. * indentation.
  1334. * @param indent The indentation of the top level.
  1335. * @return a printable, displayable, transmittable
  1336. * representation of the object, beginning
  1337. * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  1338. * with <code>}</code>&nbsp;<small>(right brace)</small>.
  1339. * @throws JSONException If the object contains an invalid number.
  1340. */
  1341. @SuppressWarnings("cast")
  1342. static String valueToString(Object value, int indentFactor, int indent)
  1343. throws JSONException {
  1344. if (value == null || value.equals(null)) {
  1345. return "null";
  1346. }
  1347. try {
  1348. if (value instanceof JSONString) {
  1349. Object o = ((JSONString)value).toJSONString();
  1350. if (o instanceof String) {
  1351. return (String)o;
  1352. }
  1353. }
  1354. } catch (Exception e) {
  1355. /* forget about it */
  1356. }
  1357. if (value instanceof Number) {
  1358. return numberToString((Number) value);
  1359. }
  1360. if (value instanceof Boolean) {
  1361. return value.toString();
  1362. }
  1363. if (value instanceof JSONObject) {
  1364. return ((JSONObject)value).toString(indentFactor, indent);
  1365. }
  1366. if (value instanceof JSONArray) {
  1367. return ((JSONArray)value).toString(indentFactor, indent);
  1368. }
  1369. if (value instanceof Map<?, ?>) {
  1370. return new JSONObject((Map<?, ?>)value).toString(indentFactor, indent);
  1371. }
  1372. if (value instanceof Collection<?>) {
  1373. return new JSONArray((Collection<?>) value).toString(indentFactor, indent);
  1374. }
  1375. if (value.getClass().isArray()) {
  1376. return new JSONArray(value).toString(indentFactor, indent);
  1377. }
  1378. return quote(value.toString());
  1379. }
  1380. /**
  1381. * Write the contents of the JSONObject as JSON text to a writer.
  1382. * For compactness, no whitespace is added.
  1383. * <p>
  1384. * Warning: This method assumes that the data structure is acyclical.
  1385. *
  1386. * @return The writer.
  1387. * @throws JSONException
  1388. */
  1389. public Writer write(Writer writer) throws JSONException {
  1390. try {
  1391. boolean b = false;
  1392. Iterator<?> keys = keys();
  1393. writer.write('{');
  1394. while (keys.hasNext()) {
  1395. if (b) {
  1396. writer.write(',');
  1397. }
  1398. Object k = keys.next();
  1399. writer.write(quote(k.toString()));
  1400. writer.write(':');
  1401. Object v = this.map.get(k);
  1402. if (v instanceof JSONObject) {
  1403. ((JSONObject)v).write(writer);
  1404. } else if (v instanceof JSONArray) {
  1405. ((JSONArray)v).write(writer);
  1406. } else {
  1407. writer.write(valueToString(v));
  1408. }
  1409. b = true;
  1410. }
  1411. writer.write('}');
  1412. return writer;
  1413. } catch (IOException e) {
  1414. throw new JSONException(e);
  1415. }
  1416. }
  1417. }