PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/JSONArray.java

http://github.com/douglascrockford/JSON-java
Java | 1521 lines | 570 code | 86 blank | 865 comment | 106 complexity | ee6837cc05f1741fa49f2519630dfdb9 MD5 | raw file
Possible License(s): JSON

Large files files are truncated, but you can click here to view the full 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.StringWriter;
  23. import java.io.Writer;
  24. import java.lang.reflect.Array;
  25. import java.math.BigDecimal;
  26. import java.math.BigInteger;
  27. import java.util.ArrayList;
  28. import java.util.Collection;
  29. import java.util.Iterator;
  30. import java.util.List;
  31. import java.util.Map;
  32. /**
  33. * A JSONArray is an ordered sequence of values. Its external text form is a
  34. * string wrapped in square brackets with commas separating the values. The
  35. * internal form is an object having <code>get</code> and <code>opt</code>
  36. * methods for accessing the values by index, and <code>put</code> methods for
  37. * adding or replacing values. 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
  40. * <code>JSONObject.NULL object</code>.
  41. * <p>
  42. * The constructor can convert a JSON text into a Java object. The
  43. * <code>toString</code> method converts to JSON text.
  44. * <p>
  45. * A <code>get</code> method returns a value if one can be found, and throws an
  46. * exception if one cannot be found. An <code>opt</code> method returns a
  47. * default value instead of throwing an exception, and so is useful for
  48. * obtaining optional values.
  49. * <p>
  50. * The generic <code>get()</code> and <code>opt()</code> methods return an
  51. * object which you can cast or query for type. There are also typed
  52. * <code>get</code> and <code>opt</code> methods that do type checking and type
  53. * coercion for you.
  54. * <p>
  55. * The texts produced by the <code>toString</code> methods strictly conform to
  56. * JSON syntax rules. The constructors are more forgiving in the texts they will
  57. * accept:
  58. * <ul>
  59. * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just
  60. * before the closing bracket.</li>
  61. * <li>The <code>null</code> value will be inserted when there is <code>,</code>
  62. * &nbsp;<small>(comma)</small> elision.</li>
  63. * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single
  64. * quote)</small>.</li>
  65. * <li>Strings do not need to be quoted at all if they do not begin with a quote
  66. * or single quote, and if they do not contain leading or trailing spaces, and
  67. * if they do not contain any of these characters:
  68. * <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and
  69. * if they are not the reserved words <code>true</code>, <code>false</code>, or
  70. * <code>null</code>.</li>
  71. * </ul>
  72. *
  73. * @author JSON.org
  74. * @version 2016-08/15
  75. */
  76. public class JSONArray implements Iterable<Object> {
  77. /**
  78. * The arrayList where the JSONArray's properties are kept.
  79. */
  80. private final ArrayList<Object> myArrayList;
  81. /**
  82. * Construct an empty JSONArray.
  83. */
  84. public JSONArray() {
  85. this.myArrayList = new ArrayList<Object>();
  86. }
  87. /**
  88. * Construct a JSONArray from a JSONTokener.
  89. *
  90. * @param x
  91. * A JSONTokener
  92. * @throws JSONException
  93. * If there is a syntax error.
  94. */
  95. public JSONArray(JSONTokener x) throws JSONException {
  96. this();
  97. if (x.nextClean() != '[') {
  98. throw x.syntaxError("A JSONArray text must start with '['");
  99. }
  100. char nextChar = x.nextClean();
  101. if (nextChar == 0) {
  102. // array is unclosed. No ']' found, instead EOF
  103. throw x.syntaxError("Expected a ',' or ']'");
  104. }
  105. if (nextChar != ']') {
  106. x.back();
  107. for (;;) {
  108. if (x.nextClean() == ',') {
  109. x.back();
  110. this.myArrayList.add(JSONObject.NULL);
  111. } else {
  112. x.back();
  113. this.myArrayList.add(x.nextValue());
  114. }
  115. switch (x.nextClean()) {
  116. case 0:
  117. // array is unclosed. No ']' found, instead EOF
  118. throw x.syntaxError("Expected a ',' or ']'");
  119. case ',':
  120. nextChar = x.nextClean();
  121. if (nextChar == 0) {
  122. // array is unclosed. No ']' found, instead EOF
  123. throw x.syntaxError("Expected a ',' or ']'");
  124. }
  125. if (nextChar == ']') {
  126. return;
  127. }
  128. x.back();
  129. break;
  130. case ']':
  131. return;
  132. default:
  133. throw x.syntaxError("Expected a ',' or ']'");
  134. }
  135. }
  136. }
  137. }
  138. /**
  139. * Construct a JSONArray from a source JSON text.
  140. *
  141. * @param source
  142. * A string that begins with <code>[</code>&nbsp;<small>(left
  143. * bracket)</small> and ends with <code>]</code>
  144. * &nbsp;<small>(right bracket)</small>.
  145. * @throws JSONException
  146. * If there is a syntax error.
  147. */
  148. public JSONArray(String source) throws JSONException {
  149. this(new JSONTokener(source));
  150. }
  151. /**
  152. * Construct a JSONArray from a Collection.
  153. *
  154. * @param collection
  155. * A Collection.
  156. */
  157. public JSONArray(Collection<?> collection) {
  158. if (collection == null) {
  159. this.myArrayList = new ArrayList<Object>();
  160. } else {
  161. this.myArrayList = new ArrayList<Object>(collection.size());
  162. for (Object o: collection){
  163. this.myArrayList.add(JSONObject.wrap(o));
  164. }
  165. }
  166. }
  167. /**
  168. * Construct a JSONArray from an array.
  169. *
  170. * @param array
  171. * Array. If the parameter passed is null, or not an array, an
  172. * exception will be thrown.
  173. *
  174. * @throws JSONException
  175. * If not an array or if an array value is non-finite number.
  176. * @throws NullPointerException
  177. * Thrown if the array parameter is null.
  178. */
  179. public JSONArray(Object array) throws JSONException {
  180. this();
  181. if (array.getClass().isArray()) {
  182. int length = Array.getLength(array);
  183. this.myArrayList.ensureCapacity(length);
  184. for (int i = 0; i < length; i += 1) {
  185. this.put(JSONObject.wrap(Array.get(array, i)));
  186. }
  187. } else {
  188. throw new JSONException(
  189. "JSONArray initial value should be a string or collection or array.");
  190. }
  191. }
  192. @Override
  193. public Iterator<Object> iterator() {
  194. return this.myArrayList.iterator();
  195. }
  196. /**
  197. * Get the object value associated with an index.
  198. *
  199. * @param index
  200. * The index must be between 0 and length() - 1.
  201. * @return An object value.
  202. * @throws JSONException
  203. * If there is no value for the index.
  204. */
  205. public Object get(int index) throws JSONException {
  206. Object object = this.opt(index);
  207. if (object == null) {
  208. throw new JSONException("JSONArray[" + index + "] not found.");
  209. }
  210. return object;
  211. }
  212. /**
  213. * Get the boolean value associated with an index. The string values "true"
  214. * and "false" are converted to boolean.
  215. *
  216. * @param index
  217. * The index must be between 0 and length() - 1.
  218. * @return The truth.
  219. * @throws JSONException
  220. * If there is no value for the index or if the value is not
  221. * convertible to boolean.
  222. */
  223. public boolean getBoolean(int index) throws JSONException {
  224. Object object = this.get(index);
  225. if (object.equals(Boolean.FALSE)
  226. || (object instanceof String && ((String) object)
  227. .equalsIgnoreCase("false"))) {
  228. return false;
  229. } else if (object.equals(Boolean.TRUE)
  230. || (object instanceof String && ((String) object)
  231. .equalsIgnoreCase("true"))) {
  232. return true;
  233. }
  234. throw wrongValueFormatException(index, "boolean", null);
  235. }
  236. /**
  237. * Get the double value associated with an index.
  238. *
  239. * @param index
  240. * The index must be between 0 and length() - 1.
  241. * @return The value.
  242. * @throws JSONException
  243. * If the key is not found or if the value cannot be converted
  244. * to a number.
  245. */
  246. public double getDouble(int index) throws JSONException {
  247. final Object object = this.get(index);
  248. if(object instanceof Number) {
  249. return ((Number)object).doubleValue();
  250. }
  251. try {
  252. return Double.parseDouble(object.toString());
  253. } catch (Exception e) {
  254. throw wrongValueFormatException(index, "double", e);
  255. }
  256. }
  257. /**
  258. * Get the float value associated with a key.
  259. *
  260. * @param index
  261. * The index must be between 0 and length() - 1.
  262. * @return The numeric value.
  263. * @throws JSONException
  264. * if the key is not found or if the value is not a Number
  265. * object and cannot be converted to a number.
  266. */
  267. public float getFloat(int index) throws JSONException {
  268. final Object object = this.get(index);
  269. if(object instanceof Number) {
  270. return ((Float)object).floatValue();
  271. }
  272. try {
  273. return Float.parseFloat(object.toString());
  274. } catch (Exception e) {
  275. throw wrongValueFormatException(index, "float", e);
  276. }
  277. }
  278. /**
  279. * Get the Number value associated with a key.
  280. *
  281. * @param index
  282. * The index must be between 0 and length() - 1.
  283. * @return The numeric value.
  284. * @throws JSONException
  285. * if the key is not found or if the value is not a Number
  286. * object and cannot be converted to a number.
  287. */
  288. public Number getNumber(int index) throws JSONException {
  289. Object object = this.get(index);
  290. try {
  291. if (object instanceof Number) {
  292. return (Number)object;
  293. }
  294. return JSONObject.stringToNumber(object.toString());
  295. } catch (Exception e) {
  296. throw wrongValueFormatException(index, "number", e);
  297. }
  298. }
  299. /**
  300. * Get the enum value associated with an index.
  301. *
  302. * @param <E>
  303. * Enum Type
  304. * @param clazz
  305. * The type of enum to retrieve.
  306. * @param index
  307. * The index must be between 0 and length() - 1.
  308. * @return The enum value at the index location
  309. * @throws JSONException
  310. * if the key is not found or if the value cannot be converted
  311. * to an enum.
  312. */
  313. public <E extends Enum<E>> E getEnum(Class<E> clazz, int index) throws JSONException {
  314. E val = optEnum(clazz, index);
  315. if(val==null) {
  316. // JSONException should really take a throwable argument.
  317. // If it did, I would re-implement this with the Enum.valueOf
  318. // method and place any thrown exception in the JSONException
  319. throw wrongValueFormatException(index, "enum of type "
  320. + JSONObject.quote(clazz.getSimpleName()), null);
  321. }
  322. return val;
  323. }
  324. /**
  325. * Get the BigDecimal value associated with an index. If the value is float
  326. * or double, the the {@link BigDecimal#BigDecimal(double)} constructor
  327. * will be used. See notes on the constructor for conversion issues that
  328. * may arise.
  329. *
  330. * @param index
  331. * The index must be between 0 and length() - 1.
  332. * @return The value.
  333. * @throws JSONException
  334. * If the key is not found or if the value cannot be converted
  335. * to a BigDecimal.
  336. */
  337. public BigDecimal getBigDecimal (int index) throws JSONException {
  338. Object object = this.get(index);
  339. BigDecimal val = JSONObject.objectToBigDecimal(object, null);
  340. if(val == null) {
  341. throw wrongValueFormatException(index, "BigDecimal", object, null);
  342. }
  343. return val;
  344. }
  345. /**
  346. * Get the BigInteger value associated with an index.
  347. *
  348. * @param index
  349. * The index must be between 0 and length() - 1.
  350. * @return The value.
  351. * @throws JSONException
  352. * If the key is not found or if the value cannot be converted
  353. * to a BigInteger.
  354. */
  355. public BigInteger getBigInteger (int index) throws JSONException {
  356. Object object = this.get(index);
  357. BigInteger val = JSONObject.objectToBigInteger(object, null);
  358. if(val == null) {
  359. throw wrongValueFormatException(index, "BigInteger", object, null);
  360. }
  361. return val;
  362. }
  363. /**
  364. * Get the int value associated with an index.
  365. *
  366. * @param index
  367. * The index must be between 0 and length() - 1.
  368. * @return The value.
  369. * @throws JSONException
  370. * If the key is not found or if the value is not a number.
  371. */
  372. public int getInt(int index) throws JSONException {
  373. final Object object = this.get(index);
  374. if(object instanceof Number) {
  375. return ((Number)object).intValue();
  376. }
  377. try {
  378. return Integer.parseInt(object.toString());
  379. } catch (Exception e) {
  380. throw wrongValueFormatException(index, "int", e);
  381. }
  382. }
  383. /**
  384. * Get the JSONArray associated with an index.
  385. *
  386. * @param index
  387. * The index must be between 0 and length() - 1.
  388. * @return A JSONArray value.
  389. * @throws JSONException
  390. * If there is no value for the index. or if the value is not a
  391. * JSONArray
  392. */
  393. public JSONArray getJSONArray(int index) throws JSONException {
  394. Object object = this.get(index);
  395. if (object instanceof JSONArray) {
  396. return (JSONArray) object;
  397. }
  398. throw wrongValueFormatException(index, "JSONArray", null);
  399. }
  400. /**
  401. * Get the JSONObject associated with an index.
  402. *
  403. * @param index
  404. * subscript
  405. * @return A JSONObject value.
  406. * @throws JSONException
  407. * If there is no value for the index or if the value is not a
  408. * JSONObject
  409. */
  410. public JSONObject getJSONObject(int index) throws JSONException {
  411. Object object = this.get(index);
  412. if (object instanceof JSONObject) {
  413. return (JSONObject) object;
  414. }
  415. throw wrongValueFormatException(index, "JSONObject", null);
  416. }
  417. /**
  418. * Get the long value associated with an index.
  419. *
  420. * @param index
  421. * The index must be between 0 and length() - 1.
  422. * @return The value.
  423. * @throws JSONException
  424. * If the key is not found or if the value cannot be converted
  425. * to a number.
  426. */
  427. public long getLong(int index) throws JSONException {
  428. final Object object = this.get(index);
  429. if(object instanceof Number) {
  430. return ((Number)object).longValue();
  431. }
  432. try {
  433. return Long.parseLong(object.toString());
  434. } catch (Exception e) {
  435. throw wrongValueFormatException(index, "long", e);
  436. }
  437. }
  438. /**
  439. * Get the string associated with an index.
  440. *
  441. * @param index
  442. * The index must be between 0 and length() - 1.
  443. * @return A string value.
  444. * @throws JSONException
  445. * If there is no string value for the index.
  446. */
  447. public String getString(int index) throws JSONException {
  448. Object object = this.get(index);
  449. if (object instanceof String) {
  450. return (String) object;
  451. }
  452. throw wrongValueFormatException(index, "String", null);
  453. }
  454. /**
  455. * Determine if the value is <code>null</code>.
  456. *
  457. * @param index
  458. * The index must be between 0 and length() - 1.
  459. * @return true if the value at the index is <code>null</code>, or if there is no value.
  460. */
  461. public boolean isNull(int index) {
  462. return JSONObject.NULL.equals(this.opt(index));
  463. }
  464. /**
  465. * Make a string from the contents of this JSONArray. The
  466. * <code>separator</code> string is inserted between each element. Warning:
  467. * This method assumes that the data structure is acyclical.
  468. *
  469. * @param separator
  470. * A string that will be inserted between the elements.
  471. * @return a string.
  472. * @throws JSONException
  473. * If the array contains an invalid number.
  474. */
  475. public String join(String separator) throws JSONException {
  476. int len = this.length();
  477. if (len == 0) {
  478. return "";
  479. }
  480. StringBuilder sb = new StringBuilder(
  481. JSONObject.valueToString(this.myArrayList.get(0)));
  482. for (int i = 1; i < len; i++) {
  483. sb.append(separator)
  484. .append(JSONObject.valueToString(this.myArrayList.get(i)));
  485. }
  486. return sb.toString();
  487. }
  488. /**
  489. * Get the number of elements in the JSONArray, included nulls.
  490. *
  491. * @return The length (or size).
  492. */
  493. public int length() {
  494. return this.myArrayList.size();
  495. }
  496. /**
  497. * Get the optional object value associated with an index.
  498. *
  499. * @param index
  500. * The index must be between 0 and length() - 1. If not, null is returned.
  501. * @return An object value, or null if there is no object at that index.
  502. */
  503. public Object opt(int index) {
  504. return (index < 0 || index >= this.length()) ? null : this.myArrayList
  505. .get(index);
  506. }
  507. /**
  508. * Get the optional boolean value associated with an index. It returns false
  509. * if there is no value at that index, or if the value is not Boolean.TRUE
  510. * or the String "true".
  511. *
  512. * @param index
  513. * The index must be between 0 and length() - 1.
  514. * @return The truth.
  515. */
  516. public boolean optBoolean(int index) {
  517. return this.optBoolean(index, false);
  518. }
  519. /**
  520. * Get the optional boolean value associated with an index. It returns the
  521. * defaultValue if there is no value at that index or if it is not a Boolean
  522. * or the String "true" or "false" (case insensitive).
  523. *
  524. * @param index
  525. * The index must be between 0 and length() - 1.
  526. * @param defaultValue
  527. * A boolean default.
  528. * @return The truth.
  529. */
  530. public boolean optBoolean(int index, boolean defaultValue) {
  531. try {
  532. return this.getBoolean(index);
  533. } catch (Exception e) {
  534. return defaultValue;
  535. }
  536. }
  537. /**
  538. * Get the optional double value associated with an index. NaN is returned
  539. * if there is no value for the index, or if the value is not a number and
  540. * cannot be converted to a number.
  541. *
  542. * @param index
  543. * The index must be between 0 and length() - 1.
  544. * @return The value.
  545. */
  546. public double optDouble(int index) {
  547. return this.optDouble(index, Double.NaN);
  548. }
  549. /**
  550. * Get the optional double value associated with an index. The defaultValue
  551. * is returned if there is no value for the index, or if the value is not a
  552. * number and cannot be converted to a number.
  553. *
  554. * @param index
  555. * subscript
  556. * @param defaultValue
  557. * The default value.
  558. * @return The value.
  559. */
  560. public double optDouble(int index, double defaultValue) {
  561. final Number val = this.optNumber(index, null);
  562. if (val == null) {
  563. return defaultValue;
  564. }
  565. final double doubleValue = val.doubleValue();
  566. // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
  567. // return defaultValue;
  568. // }
  569. return doubleValue;
  570. }
  571. /**
  572. * Get the optional float value associated with an index. NaN is returned
  573. * if there is no value for the index, or if the value is not a number and
  574. * cannot be converted to a number.
  575. *
  576. * @param index
  577. * The index must be between 0 and length() - 1.
  578. * @return The value.
  579. */
  580. public float optFloat(int index) {
  581. return this.optFloat(index, Float.NaN);
  582. }
  583. /**
  584. * Get the optional float value associated with an index. The defaultValue
  585. * is returned if there is no value for the index, or if the value is not a
  586. * number and cannot be converted to a number.
  587. *
  588. * @param index
  589. * subscript
  590. * @param defaultValue
  591. * The default value.
  592. * @return The value.
  593. */
  594. public float optFloat(int index, float defaultValue) {
  595. final Number val = this.optNumber(index, null);
  596. if (val == null) {
  597. return defaultValue;
  598. }
  599. final float floatValue = val.floatValue();
  600. // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) {
  601. // return floatValue;
  602. // }
  603. return floatValue;
  604. }
  605. /**
  606. * Get the optional int value associated with an index. Zero is returned if
  607. * there is no value for the index, or if the value is not a number and
  608. * cannot be converted to a number.
  609. *
  610. * @param index
  611. * The index must be between 0 and length() - 1.
  612. * @return The value.
  613. */
  614. public int optInt(int index) {
  615. return this.optInt(index, 0);
  616. }
  617. /**
  618. * Get the optional int value associated with an index. The defaultValue is
  619. * returned if there is no value for the index, or if the value is not a
  620. * number and cannot be converted to a number.
  621. *
  622. * @param index
  623. * The index must be between 0 and length() - 1.
  624. * @param defaultValue
  625. * The default value.
  626. * @return The value.
  627. */
  628. public int optInt(int index, int defaultValue) {
  629. final Number val = this.optNumber(index, null);
  630. if (val == null) {
  631. return defaultValue;
  632. }
  633. return val.intValue();
  634. }
  635. /**
  636. * Get the enum value associated with a key.
  637. *
  638. * @param <E>
  639. * Enum Type
  640. * @param clazz
  641. * The type of enum to retrieve.
  642. * @param index
  643. * The index must be between 0 and length() - 1.
  644. * @return The enum value at the index location or null if not found
  645. */
  646. public <E extends Enum<E>> E optEnum(Class<E> clazz, int index) {
  647. return this.optEnum(clazz, index, null);
  648. }
  649. /**
  650. * Get the enum value associated with a key.
  651. *
  652. * @param <E>
  653. * Enum Type
  654. * @param clazz
  655. * The type of enum to retrieve.
  656. * @param index
  657. * The index must be between 0 and length() - 1.
  658. * @param defaultValue
  659. * The default in case the value is not found
  660. * @return The enum value at the index location or defaultValue if
  661. * the value is not found or cannot be assigned to clazz
  662. */
  663. public <E extends Enum<E>> E optEnum(Class<E> clazz, int index, E defaultValue) {
  664. try {
  665. Object val = this.opt(index);
  666. if (JSONObject.NULL.equals(val)) {
  667. return defaultValue;
  668. }
  669. if (clazz.isAssignableFrom(val.getClass())) {
  670. // we just checked it!
  671. @SuppressWarnings("unchecked")
  672. E myE = (E) val;
  673. return myE;
  674. }
  675. return Enum.valueOf(clazz, val.toString());
  676. } catch (IllegalArgumentException e) {
  677. return defaultValue;
  678. } catch (NullPointerException e) {
  679. return defaultValue;
  680. }
  681. }
  682. /**
  683. * Get the optional BigInteger value associated with an index. The
  684. * defaultValue is returned if there is no value for the index, or if the
  685. * value is not a number and cannot be converted to a number.
  686. *
  687. * @param index
  688. * The index must be between 0 and length() - 1.
  689. * @param defaultValue
  690. * The default value.
  691. * @return The value.
  692. */
  693. public BigInteger optBigInteger(int index, BigInteger defaultValue) {
  694. Object val = this.opt(index);
  695. return JSONObject.objectToBigInteger(val, defaultValue);
  696. }
  697. /**
  698. * Get the optional BigDecimal value associated with an index. The
  699. * defaultValue is returned if there is no value for the index, or if the
  700. * value is not a number and cannot be converted to a number. If the value
  701. * is float or double, the the {@link BigDecimal#BigDecimal(double)}
  702. * constructor will be used. See notes on the constructor for conversion
  703. * issues that may arise.
  704. *
  705. * @param index
  706. * The index must be between 0 and length() - 1.
  707. * @param defaultValue
  708. * The default value.
  709. * @return The value.
  710. */
  711. public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) {
  712. Object val = this.opt(index);
  713. return JSONObject.objectToBigDecimal(val, defaultValue);
  714. }
  715. /**
  716. * Get the optional JSONArray associated with an index.
  717. *
  718. * @param index
  719. * subscript
  720. * @return A JSONArray value, or null if the index has no value, or if the
  721. * value is not a JSONArray.
  722. */
  723. public JSONArray optJSONArray(int index) {
  724. Object o = this.opt(index);
  725. return o instanceof JSONArray ? (JSONArray) o : null;
  726. }
  727. /**
  728. * Get the optional JSONObject associated with an index. Null is returned if
  729. * the key is not found, or null if the index has no value, or if the value
  730. * is not a JSONObject.
  731. *
  732. * @param index
  733. * The index must be between 0 and length() - 1.
  734. * @return A JSONObject value.
  735. */
  736. public JSONObject optJSONObject(int index) {
  737. Object o = this.opt(index);
  738. return o instanceof JSONObject ? (JSONObject) o : null;
  739. }
  740. /**
  741. * Get the optional long value associated with an index. Zero is returned if
  742. * there is no value for the index, or if the value is not a number and
  743. * cannot be converted to a number.
  744. *
  745. * @param index
  746. * The index must be between 0 and length() - 1.
  747. * @return The value.
  748. */
  749. public long optLong(int index) {
  750. return this.optLong(index, 0);
  751. }
  752. /**
  753. * Get the optional long value associated with an index. The defaultValue is
  754. * returned if there is no value for the index, or if the value is not a
  755. * number and cannot be converted to a number.
  756. *
  757. * @param index
  758. * The index must be between 0 and length() - 1.
  759. * @param defaultValue
  760. * The default value.
  761. * @return The value.
  762. */
  763. public long optLong(int index, long defaultValue) {
  764. final Number val = this.optNumber(index, null);
  765. if (val == null) {
  766. return defaultValue;
  767. }
  768. return val.longValue();
  769. }
  770. /**
  771. * Get an optional {@link Number} value associated with a key, or <code>null</code>
  772. * if there is no such key or if the value is not a number. If the value is a string,
  773. * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method
  774. * would be used in cases where type coercion of the number value is unwanted.
  775. *
  776. * @param index
  777. * The index must be between 0 and length() - 1.
  778. * @return An object which is the value.
  779. */
  780. public Number optNumber(int index) {
  781. return this.optNumber(index, null);
  782. }
  783. /**
  784. * Get an optional {@link Number} value associated with a key, or the default if there
  785. * is no such key or if the value is not a number. If the value is a string,
  786. * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method
  787. * would be used in cases where type coercion of the number value is unwanted.
  788. *
  789. * @param index
  790. * The index must be between 0 and length() - 1.
  791. * @param defaultValue
  792. * The default.
  793. * @return An object which is the value.
  794. */
  795. public Number optNumber(int index, Number defaultValue) {
  796. Object val = this.opt(index);
  797. if (JSONObject.NULL.equals(val)) {
  798. return defaultValue;
  799. }
  800. if (val instanceof Number){
  801. return (Number) val;
  802. }
  803. if (val instanceof String) {
  804. try {
  805. return JSONObject.stringToNumber((String) val);
  806. } catch (Exception e) {
  807. return defaultValue;
  808. }
  809. }
  810. return defaultValue;
  811. }
  812. /**
  813. * Get the optional string value associated with an index. It returns an
  814. * empty string if there is no value at that index. If the value is not a
  815. * string and is not null, then it is converted to a string.
  816. *
  817. * @param index
  818. * The index must be between 0 and length() - 1.
  819. * @return A String value.
  820. */
  821. public String optString(int index) {
  822. return this.optString(index, "");
  823. }
  824. /**
  825. * Get the optional string associated with an index. The defaultValue is
  826. * returned if the key is not found.
  827. *
  828. * @param index
  829. * The index must be between 0 and length() - 1.
  830. * @param defaultValue
  831. * The default value.
  832. * @return A String value.
  833. */
  834. public String optString(int index, String defaultValue) {
  835. Object object = this.opt(index);
  836. return JSONObject.NULL.equals(object) ? defaultValue : object
  837. .toString();
  838. }
  839. /**
  840. * Append a boolean value. This increases the array's length by one.
  841. *
  842. * @param value
  843. * A boolean value.
  844. * @return this.
  845. */
  846. public JSONArray put(boolean value) {
  847. return this.put(value ? Boolean.TRUE : Boolean.FALSE);
  848. }
  849. /**
  850. * Put a value in the JSONArray, where the value will be a JSONArray which
  851. * is produced from a Collection.
  852. *
  853. * @param value
  854. * A Collection value.
  855. * @return this.
  856. * @throws JSONException
  857. * If the value is non-finite number.
  858. */
  859. public JSONArray put(Collection<?> value) {
  860. return this.put(new JSONArray(value));
  861. }
  862. /**
  863. * Append a double value. This increases the array's length by one.
  864. *
  865. * @param value
  866. * A double value.
  867. * @return this.
  868. * @throws JSONException
  869. * if the value is not finite.
  870. */
  871. public JSONArray put(double value) throws JSONException {
  872. return this.put(Double.valueOf(value));
  873. }
  874. /**
  875. * Append a float value. This increases the array's length by one.
  876. *
  877. * @param value
  878. * A float value.
  879. * @return this.
  880. * @throws JSONException
  881. * if the value is not finite.
  882. */
  883. public JSONArray put(float value) throws JSONException {
  884. return this.put(Float.valueOf(value));
  885. }
  886. /**
  887. * Append an int value. This increases the array's length by one.
  888. *
  889. * @param value
  890. * An int value.
  891. * @return this.
  892. */
  893. public JSONArray put(int value) {
  894. return this.put(Integer.valueOf(value));
  895. }
  896. /**
  897. * Append an long value. This increases the array's length by one.
  898. *
  899. * @param value
  900. * A long value.
  901. * @return this.
  902. */
  903. public JSONArray put(long value) {
  904. return this.put(Long.valueOf(value));
  905. }
  906. /**
  907. * Put a value in the JSONArray, where the value will be a JSONObject which
  908. * is produced from a Map.
  909. *
  910. * @param value
  911. * A Map value.
  912. * @return this.
  913. * @throws JSONException
  914. * If a value in the map is non-finite number.
  915. * @throws NullPointerException
  916. * If a key in the map is <code>null</code>
  917. */
  918. public JSONArray put(Map<?, ?> value) {
  919. return this.put(new JSONObject(value));
  920. }
  921. /**
  922. * Append an object value. This increases the array's length by one.
  923. *
  924. * @param value
  925. * An object value. The value should be a Boolean, Double,
  926. * Integer, JSONArray, JSONObject, Long, or String, or the
  927. * JSONObject.NULL object.
  928. * @return this.
  929. * @throws JSONException
  930. * If the value is non-finite number.
  931. */
  932. public JSONArray put(Object value) {
  933. JSONObject.testValidity(value);
  934. this.myArrayList.add(value);
  935. return this;
  936. }
  937. /**
  938. * Put or replace a boolean value in the JSONArray. If the index is greater
  939. * than the length of the JSONArray, then null elements will be added as
  940. * necessary to pad it out.
  941. *
  942. * @param index
  943. * The subscript.
  944. * @param value
  945. * A boolean value.
  946. * @return this.
  947. * @throws JSONException
  948. * If the index is negative.
  949. */
  950. public JSONArray put(int index, boolean value) throws JSONException {
  951. return this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
  952. }
  953. /**
  954. * Put a value in the JSONArray, where the value will be a JSONArray which
  955. * is produced from a Collection.
  956. *
  957. * @param index
  958. * The subscript.
  959. * @param value
  960. * A Collection value.
  961. * @return this.
  962. * @throws JSONException
  963. * If the index is negative or if the value is non-finite.
  964. */
  965. public JSONArray put(int index, Collection<?> value) throws JSONException {
  966. return this.put(index, new JSONArray(value));
  967. }
  968. /**
  969. * Put or replace a double value. If the index is greater than the length of
  970. * the JSONArray, then null elements will be added as necessary to pad it
  971. * out.
  972. *
  973. * @param index
  974. * The subscript.
  975. * @param value
  976. * A double value.
  977. * @return this.
  978. * @throws JSONException
  979. * If the index is negative or if the value is non-finite.
  980. */
  981. public JSONArray put(int index, double value) throws JSONException {
  982. return this.put(index, Double.valueOf(value));
  983. }
  984. /**
  985. * Put or replace a float value. If the index is greater than the length of
  986. * the JSONArray, then null elements will be added as necessary to pad it
  987. * out.
  988. *
  989. * @param index
  990. * The subscript.
  991. * @param value
  992. * A float value.
  993. * @return this.
  994. * @throws JSONException
  995. * If the index is negative or if the value is non-finite.
  996. */
  997. public JSONArray put(int index, float value) throws JSONException {
  998. return this.put(index, Float.valueOf(value));
  999. }
  1000. /**
  1001. * Put or replace an int value. If the index is greater than the length of
  1002. * the JSONArray, then null elements will be added as necessary to pad it
  1003. * out.
  1004. *
  1005. * @param index
  1006. * The subscript.
  1007. * @param value
  1008. * An int value.
  1009. * @return this.
  1010. * @throws JSONException
  1011. * If the index is negative.
  1012. */
  1013. public JSONArray put(int index, int value) throws JSONException {
  1014. return this.put(index, Integer.valueOf(value));
  1015. }
  1016. /**
  1017. * Put or replace a long value. If the index is greater than the length of
  1018. * the JSONArray, then null elements will be added as necessary to pad it
  1019. * out.
  1020. *
  1021. * @param index
  1022. * The subscript.
  1023. * @param value
  1024. * A long value.
  1025. * @return this.
  1026. * @throws JSONException
  1027. * If the index is negative.
  1028. */
  1029. public JSONArray put(int index, long value) throws JSONException {
  1030. return this.put(index, Long.valueOf(value));
  1031. }
  1032. /**
  1033. * Put a value in the JSONArray, where the value will be a JSONObject that
  1034. * is produced from a Map.
  1035. *
  1036. * @param index
  1037. * The subscript.
  1038. * @param value
  1039. * The Map value.
  1040. * @return this.
  1041. * @throws JSONException
  1042. * If the index is negative or if the the value is an invalid
  1043. * number.
  1044. * @throws NullPointerException
  1045. * If a key in the map is <code>null</code>
  1046. */
  1047. public JSONArray put(int index, Map<?, ?> value) throws JSONException {
  1048. this.put(index, new JSONObject(value));
  1049. return this;
  1050. }
  1051. /**
  1052. * Put or replace an object value in the JSONArray. If the index is greater
  1053. * than the length of the JSONArray, then null elements will be added as
  1054. * necessary to pad it out.
  1055. *
  1056. * @param index
  1057. * The subscript.
  1058. * @param value
  1059. * The value to put into the array. The value should be a
  1060. * Boolean, Double, Integer, JSONArray, JSONObject, Long, or
  1061. * String, or the JSONObject.NULL object.
  1062. * @return this.
  1063. * @throws JSONException
  1064. * If the index is negative or if the the value is an invalid
  1065. * number.
  1066. */
  1067. public JSONArray put(int index, Object value) throws JSONException {
  1068. if (index < 0) {
  1069. throw new JSONException("JSONArray[" + index + "] not found.");
  1070. }
  1071. if (index < this.length()) {
  1072. JSONObject.testValidity(value);
  1073. this.myArrayList.set(index, value);
  1074. return this;
  1075. }
  1076. if(index == this.length()){
  1077. // simple append
  1078. return this.put(value);
  1079. }
  1080. // if we are inserting past the length, we want to grow the array all at once
  1081. // instead of incrementally.
  1082. this.myArrayList.ensureCapacity(index + 1);
  1083. while (index != this.length()) {
  1084. // we don't need to test validity of NULL objects
  1085. this.myArrayList.add(JSONObject.NULL);
  1086. }
  1087. return this.put(value);
  1088. }
  1089. /**
  1090. * Creates a JSONPointer using an initialization string and tries to
  1091. * match it to an item within this JSONArray. For example, given a
  1092. * JSONArray initialized with this document:
  1093. * <pre>
  1094. * [
  1095. * {"b":"c"}
  1096. * ]
  1097. * </pre>
  1098. * and this JSONPointer string:
  1099. * <pre>
  1100. * "/0/b"
  1101. * </pre>
  1102. * Then this method will return the String "c"
  1103. * A JSONPointerException may be thrown from code called by this method.
  1104. *
  1105. * @param jsonPointer string that can be used to create a JSONPointer
  1106. * @return the item matched by the JSONPointer, otherwise null
  1107. */
  1108. public Object query(String jsonPointer) {
  1109. return query(new JSONPointer(jsonPointer));
  1110. }
  1111. /**
  1112. * Uses a user initialized JSONPointer and tries to
  1113. * match it to an item within this JSONArray. For example, given a
  1114. * JSONArray initialized with this document:
  1115. * <pre>
  1116. * [
  1117. * {"b":"c"}
  1118. * ]
  1119. * </pre>
  1120. * and this JSONPointer:
  1121. * <pre>
  1122. * "/0/b"
  1123. * </pre>
  1124. * Then this method will return the String "c"
  1125. * A JSONPointerException may be thrown from code called by this method.
  1126. *
  1127. * @param jsonPointer string that can be used to create a JSONPointer
  1128. * @return the item matched by the JSONPointer, otherwise null
  1129. */
  1130. public Object query(JSONPointer jsonPointer) {
  1131. return jsonPointer.queryFrom(this);
  1132. }
  1133. /**
  1134. * Queries and returns a value from this object using {@code jsonPointer}, or
  1135. * returns null if the query fails due to a missing key.
  1136. *
  1137. * @param jsonPointer the string representation of the JSON pointer
  1138. * @return the queried value or {@code null}
  1139. * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
  1140. */
  1141. public Object optQuery(String jsonPointer) {
  1142. return optQuery(new JSONPointer(jsonPointer));
  1143. }
  1144. /**
  1145. * Queries and returns a value from this object using {@code jsonPointer}, or
  1146. * returns null if the query fails due to a missing key.
  1147. *
  1148. * @param jsonPointer The JSON pointer
  1149. * @return the queried value or {@code null}
  1150. * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
  1151. */
  1152. public Object optQuery(JSONPointer jsonPointer) {
  1153. try {
  1154. return jsonPointer.queryFrom(this);
  1155. } catch (JSONPointerException e) {
  1156. return null;
  1157. }
  1158. }
  1159. /**
  1160. * Remove an index and close the hole.
  1161. *
  1162. * @param index
  1163. * The index of the element to be removed.
  1164. * @return The value that was associated with the index, or null if there
  1165. * was no value.
  1166. */
  1167. public Object remove(int index) {
  1168. return index >= 0 && index < this.length()
  1169. ? this.myArrayList.remove(index)
  1170. : null;
  1171. }
  1172. /**
  1173. * Determine if two JSONArrays are similar.
  1174. * They must contain similar sequences.
  1175. *
  1176. * @param other The other JSONArray
  1177. * @return true if they are equal
  1178. */
  1179. public boolean similar(Object other) {
  1180. if (!(other instanceof JSONArray)) {
  1181. return false;
  1182. }
  1183. int len = this.length();
  1184. if (len != ((JSONArray)other).length()) {
  1185. return false;
  1186. }
  1187. for (int i = 0; i < len; i += 1) {
  1188. Object valueThis = this.myArrayList.get(i);
  1189. Object valueOther = ((JSONArray)other).myArrayList.get(i);
  1190. if(valueThis == valueOther) {
  1191. continue;
  1192. }
  1193. if(valueThis == null) {
  1194. return false;
  1195. }
  1196. if (valueThis instanceof JSONObject) {
  1197. if (!((JSONObject)valueThis).similar(valueOther)) {
  1198. return false;
  1199. }
  1200. } else if (valueThis instanceof JSONArray) {
  1201. if (!((JSONArray)valueThis).similar(valueOther)) {
  1202. return false;
  1203. }
  1204. } else if (!valueThis.equals(valueOther)) {
  1205. return false;
  1206. }
  1207. }
  1208. return true;
  1209. }
  1210. /**
  1211. * Produce a JSONObject by combining a JSONArray of names with the values of
  1212. * this JSONArray.
  1213. *
  1214. * @param names
  1215. * A JSONArray containing a list of key strings. These will be
  1216. * paired with the values.
  1217. * @return A JSONObject, or null if there are no names or if this JSONArray
  1218. * has no values.
  1219. * @throws JSONException
  1220. * If any of the names are null.
  1221. */
  1222. public JSONObject toJSONObject(JSONArray names) throws JSONException {
  1223. if (names == null || names.isEmpty() || this.isEmpty()) {
  1224. return null;
  1225. }
  1226. JSONObject jo = new JSONObject(names.length());
  1227. for (int i = 0; i < names.length(); i += 1) {
  1228. jo.put(names.getString(i), this.opt(i));
  1229. }
  1230. return jo;
  1231. }
  1232. /**
  1233. * Make a JSON text of this JSONArray. For compactness, no unnecessary
  1234. * whitespace is added. If it is not possible to produce a syntactically
  1235. * correct JSON text then null will be returned instead. This could occur if
  1236. * the array contains an invalid number.
  1237. * <p><b>
  1238. * Warning: This method assumes that the data structure is acyclical.
  1239. * </b>
  1240. *
  1241. * @return a printable, displayable, transmittable representation of the
  1242. * array.
  1243. */
  1244. @Override
  1245. public String toString() {
  1246. try {
  1247. return this.toString(0);
  1248. } catch (Exception e) {
  1249. return null;
  1250. }
  1251. }
  1252. /**
  1253. * Make a pretty-printed JSON text of this JSONArray.
  1254. *
  1255. * <p>If <code>indentFactor > 0</code> and the {@link JSONArray} has only
  1256. * one element, then the array will be output on a single line:
  1257. * <pre>{@code [1]}</pre>
  1258. *
  1259. * <p>If an array has 2 or more elements, then it will be output across
  1260. * multiple lines: <pre>{@code
  1261. * [
  1262. * 1,
  1263. * "value 2",
  1264. * 3
  1265. * ]
  1266. * }</pre>
  1267. * <p><b>
  1268. * Warning: This method assumes that the data structure is acyclical.
  1269. * </b>
  1270. *
  1271. * @param indentFactor
  1272. * The number of spaces to add to each level of indentation.
  1273. * @return a printable, displayable, transmittable representation of the
  1274. * object, beginning with <code>[</code>&nbsp;<small>(left
  1275. * bracket)</small> and ending with <code>]</code>
  1276. * &nbsp;<small>(right bracket)</small>.
  1277. * @throws JSONException
  1278. */
  1279. public String toString(int indentFactor) throws JSONException {
  1280. StringWriter sw = new StringWriter();
  1281. synchronized (sw.getBuffer()) {
  1282. return this.write(sw, indentFactor, 0).toString();
  1283. }
  1284. }
  1285. /**
  1286. * Write the contents of the JSONArray as JSON text to a writer. For
  1287. * compactness, no whitespace is added.
  1288. * <p><b>
  1289. * Warning: This method assumes that the data structure is acyclical.
  1290. *</b>
  1291. *
  1292. * @return The writer.
  1293. * @throws JSONException
  1294. */
  1295. public Writer write(Writer writer) throws JSONException {
  1296. return this.write(writer, 0, 0);
  1297. }
  1298. /**
  1299. * Write the contents of the JSONArray as JSON text to a writer.
  1300. *
  1301. * <p>If <code>indentFactor > 0</code> and the {@link JSONArray} has only
  1302. * one element, then the array will be output on a single line:
  1303. * <pre>{@code [1]}</pre>
  1304. *
  1305. * <p>If an array has 2 or more elements, then it will be output across
  1306. * multiple lines: <pre>{@code
  1307. * [
  1308. * 1,
  1309. * "value 2",
  1310. * 3
  1311. * ]
  1312. * }</pre>
  1313. * <p><b>
  1314. * Warning: This method assumes that the data structure is acyclical.
  1315. * </b>
  1316. *
  1317. * @param writer
  1318. * Writes the serialized JSON
  1319. * @param indentFactor
  1320. * The number of spaces to add to each level of indentation.
  1321. * @param indent
  1322. * The indentation of the top level.
  1323. * @return The writer.
  1324. * @throws JSONException
  1325. */
  1326. public Writer write(Writer writer, int indentFactor, int indent)
  1327. throws JSONException {
  1328. try {
  1329. boolean needsComma = false;
  1330. int length = this.length();
  1331. writer.write('[');
  1332. if (length == 1) {
  1333. try {
  1334. JSONObject.writeValue(writer, this.myArrayList.get(0),
  1335. indentFactor, indent);
  1336. } catch (Exception e) {
  1337. throw new JSONException("Unable to write JSONArray value at index: 0", e);
  1338. }
  1339. } else if (length != 0) {
  1340. final int newIndent = indent + indentFactor;
  1341. for (int i = 0; i < length; i += 1) {
  1342. if (needsComma) {
  1343. writer.write(',');
  1344. }
  1345. if (indentFactor > 0) {
  1346. writer.write('\n');
  1347. }
  1348. JSONObject.indent(writer, newIndent);
  1349. try {
  1350. JSONObject.writeValue(writer, this.myArrayList.get(i),
  1351. indentFactor, newIndent);
  1352. } catch (Exception e) {
  1353. throw new JSONException("Unable to write JSONArray value at index: " + i, e);
  1354. }
  1355. needsComma = true;
  1356. }
  1357. if (indentFactor > 0) {
  1358. writer.write('\n');
  1359. }
  1360. JSONObject.indent(writer, indent);
  1361. }
  1362. writer.write(']');
  1363. return writer;
  1364. } catch (IOException e) {
  1365. throw new JSONException(e);
  1366. }
  1367. }
  1368. /**
  1369. * Returns a java.util.List containing all of the elements in this array.
  1370. * If an element in the array is a JSONArray or JSONObject it will also
  1371. * be converted to a List and a Map respectively.
  1372. * <p>
  1373. * Warning: This method assumes that the data structure is acyclical.
  1374. *
  1375. * @return a java.util.List containing the elements of this array
  1376. */
  1377. public List<Object> toList() {
  1378. List<Object> results = new ArrayList<Object>(this.myArrayList.size());
  1379. for (Object element : this.myArrayList) {
  1380. if (element == null || JSONObject.NULL.equals(element)) {
  1381. results.add(null);
  1382. } else if (element instanceof JSONArray) {
  1383. results.add(((JSONArray) element).toList());
  1384. } else if (element instanceof JSONObject) {
  1385. results.add(((JSONObject) element).toMap());

Large files files are truncated, but you can click here to view the full file