Posted By

d3developer on 08/28/10


Tagged


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

terrerouge
cwd


JSONObject


 / Published in: Other
 

  1. public class JSONObject {
  2. /*
  3. Copyright (c) 2002 JSON.org
  4.  
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the 'Software'), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11.  
  12. The above copyright notice and this permission notice shall be included in all
  13. copies or substantial portions of the Software.
  14.  
  15. The Software shall be used for Good, not Evil.
  16.  
  17. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24. */
  25.  
  26. /*
  27. * A JSONObject is an unordered collection of name/value pairs. Its
  28. * external form is a string wrapped in curly braces with colons between the
  29. * names and values, and commas between the values and names. The internal form
  30. * is an object having <code>get</code> and <code>opt</code> methods for
  31. * accessing the values by name, and <code>put</code> methods for adding or
  32. * replacing values by name. The values can be any of these types:
  33. * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
  34. * <code>Number</code>, <code>String</code>, or the <code>JSONObject.NULL</code>
  35. * object. A JSONObject constructor can be used to convert an external form
  36. * JSON text into an internal form whose values can be retrieved with the
  37. * <code>get</code> and <code>opt</code> methods, or to convert values into a
  38. * JSON text using the <code>put</code> and <code>toString</code> methods.
  39. * A <code>get</code> method returns a value if one can be found, and throws an
  40. * exception if one cannot be found. An <code>opt</code> method returns a
  41. * default value instead of throwing an exception, and so is useful for
  42. * obtaining optional values.
  43. * <p>
  44. * The generic <code>get()</code> and <code>opt()</code> methods return an
  45. * object, which you can cast or query for type. There are also typed
  46. * <code>get</code> and <code>opt</code> methods that do type checking and type
  47. * coersion for you.
  48. * <p>
  49. * The <code>put</code> methods adds values to an object. For example, <pre>
  50. * myString = new JSONObject().put('JSON', "Hello, World!").toString();</pre>
  51. * produces the string <code>{"JSON": "Hello, World"}</code>.
  52. * <p>
  53. * The texts produced by the <code>toString</code> methods strictly conform to
  54. * the JSON sysntax rules.
  55. * The constructors are more forgiving in the texts they will accept:
  56. * <ul>
  57. * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just
  58. * before the closing brace.</li>
  59. * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single
  60. * quote)</small>.</li>
  61. * <li>Strings do not need to be quoted at all if they do not begin with a quote
  62. * or single quote, and if they do not contain leading or trailing spaces,
  63. * and if they do not contain any of these characters:
  64. * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
  65. * and if they are not the reserved words <code>true</code>,
  66. * <code>false</code>, or <code>null</code>.</li>
  67. * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as
  68. * by <code>:</code>.</li>
  69. * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as
  70. * well as by <code>,</code> <small>(comma)</small>.</li>
  71. * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or
  72. * <code>0x-</code> <small>(hex)</small> prefix.</li>
  73. * <li>Comments written in the slashshlash, slashstar, and hash conventions
  74. * will be ignored.</li>
  75. * </ul>
  76. * @author JSON.org
  77. * @version 3
  78. */
  79.  
  80. /*
  81. * Sept 2008, rhess
  82. * begin simple port of this code to Force.com Apex Code
  83. * currently this code is only building Apex objects from JSON,
  84. * not outputing JSON from Apex
  85. * Oct add valueToString
  86. */
  87. public class value {
  88. /* apex object to store one of several different data types
  89. * see : http://www.json.org/
  90. */
  91. public value() { }
  92. public value(boolean bb) { bool = bb;}
  93. public value(integer ii) {num=ii;}
  94. public value(Decimal ii) {dnum= ii;}
  95. public value(string st) {str=st;}
  96. public value( jsonobject oo) { obj = oo; }
  97. public value( list<value> vary ) { values = vary; }
  98.  
  99. public string str {get;set;}
  100. public integer num {get;set;}
  101. public double dnum {get;set;}
  102. public JSONObject obj {get;set;}
  103. public list<value> values {get;set;} // array
  104. public boolean bool {get;set;}
  105. // if all members are null, value == null
  106. // isNull()
  107. /*
  108. * value to string is used to output JSON for Google Visualization API
  109. */
  110. public string valueToString() {
  111. if ( this.bool != null ) return (this.bool?'true':'false');
  112. if ( this.str != null ) return '"'+this.str +'"';
  113. if ( this.num != null ) return String.valueof(this.num);
  114. if ( this.dnum != null ) return String.valueof(this.dnum);
  115. if ( this.values != null ) {
  116. string ret = '[';
  117. for ( value v:this.values) {
  118. //system.debug( v );
  119. ret += v.valueToString() + ',';
  120. }
  121. return ret.substring(0,ret.length()-1) + ']';
  122. }
  123. if ( this.obj != null ) {
  124. return this.obj.valueToString();
  125. }
  126. return 'null';
  127. }
  128.  
  129. } // end of class value
  130.  
  131. /* **
  132. * The map where the JSONObject's properties are kept.
  133. */
  134. private map<string,value> data = new map<string,value>();
  135.  
  136. public value getValue(string key) { return data.get(key); }
  137.  
  138. /* **
  139. * Construct an empty JSONObject.
  140. */
  141. public JSONObject() { }
  142.  
  143. /*
  144. * Construct a JSONObject from a JSONTokener.
  145. * @param x A JSONTokener object containing the source string.
  146. * @ If there is a syntax error in the source string.
  147. */
  148. public JSONObject(JSONTokener x) {
  149. this();
  150. string c;
  151. String key;
  152.  
  153. if (x.nextClean() != '{') {
  154. throw new jsonexception('A JSONObject text must begin with {');
  155. }
  156. for (;;) {
  157. c = x.nextClean();
  158. if ( c == null) {
  159. throw new jsonexception('A JSONObject text must end with }');
  160. } else if ( c== '}' ) {
  161. return;
  162. } else {
  163. x.back();
  164.  
  165. key = (string)x.nextValue().str;
  166. // system.debug( 'key is :'+key); }
  167. }
  168.  
  169. /*
  170. * The key is followed by ':'. We will also tolerate '=' or '=>'.
  171. */
  172.  
  173. c = x.nextClean();
  174. if (c == '=') {
  175. if (x.next() != '>') {
  176. x.back();
  177. }
  178. } else if (c != ':') {
  179. throw new jsonexception('Expected a : after a key');
  180. }
  181.  
  182. putOpt(key, x.nextValue()); // load next value into data map
  183.  
  184. /*
  185. * Pairs are separated by ','. We will also tolerate ';'.
  186. */
  187.  
  188. string nc = x.nextClean();
  189. if ( nc == ';' || nc == ',' ) {
  190. if (x.nextClean() == '}') {
  191. return;
  192. }
  193. x.back();
  194. } else if ( nc == '}' ) {
  195. return;
  196. } else {
  197. throw new jsonexception('Expected a , or }');
  198. }
  199. }
  200. }
  201.  
  202.  
  203. /* **
  204. * Construct a JSONObject from a source JSON text string.
  205. * This is the most commonly used JSONObject constructor.
  206. * @param source A string beginning
  207. * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  208. * with <code>}</code>&nbsp;<small>(right brace)</small>.
  209. * @exception JSONException If there is a syntax error in the source string.
  210. */
  211. public static JSONObject instance(String source) {
  212. return new JSONObject( new JSONTokener(source) );
  213. }
  214. public JSONObject (String source) {
  215. this( new JSONTokener(source) );
  216. }
  217.  
  218.  
  219. /* **
  220. * Produce a string from a double. The string 'null' will be returned if
  221. * the number is not finite.
  222. * @param d A double.
  223. * @return A String.
  224.  
  225. public static String doubleToString(double d) {
  226. if (Double.isInfinite(d) || Double.isNaN(d)) {
  227. return 'null';
  228. }
  229. // Shave off trailing zeros and decimal point, if possible.
  230. String s = Double.toString(d);
  231. if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
  232. while (s.endsWith('0')) {
  233. s = s.substring(0, s.length() - 1);
  234. }
  235. if (s.endsWith('.')) {
  236. s = s.substring(0, s.length() - 1);
  237. }
  238. }
  239. return s;
  240. }
  241. */
  242.  
  243. /* **
  244. * Get the value object associated with a key.
  245. *
  246. * @param key A key string.
  247. * @return The object associated with the key.
  248. * @throws JSONException if the key is not found.
  249. */
  250. public object get(string key) {
  251. value ret = this.data.get(key);
  252. if (ret == null) {
  253. throw new JSONException('JSONObject[' + key + '] not found.');
  254. }
  255. if ( ret.str != null ) return ret.str;
  256. if ( ret.num != null ) return ret.num;
  257. if ( ret.bool != null ) return ret.bool;
  258. system.assert( ret.obj == null , 'get cannot return nested json ojects');
  259. // array?
  260. return null;
  261. }
  262.  
  263.  
  264. /* **
  265. * Get the boolean value associated with a key.
  266. *
  267. * @param key A key string.
  268. * @return The truth.
  269. * @throws JSONException
  270. * if the value is not a Boolean or the String 'true' or 'false'.
  271. */
  272. public boolean getBoolean(String key) {
  273. Object o = this.get(key);
  274. if ( o!=null) return (boolean) o;
  275. throw new JSONException('JSONObject[' + key + '] is not a Boolean.');
  276. }
  277.  
  278.  
  279. /* **
  280. * Get the double value associated with a key.
  281. * @param key A key string.
  282. * @return The numeric value.
  283. * @ if the key is not found or
  284. * if the value is not a Number object and cannot be converted to a number.
  285.  
  286. public double getDouble(String key) {
  287. Object o = get(key);
  288. try {
  289. return o instanceof Number ?
  290. ((Number)o).doubleValue() :
  291. Double.valueOf((String)o).doubleValue();
  292. } catch (Exception e) {
  293. throw new JSONException('JSONObject[' + quote(key) +
  294. '] is not a number.');
  295. }
  296. }*/
  297.  
  298.  
  299. /* **
  300. * Get the int value associated with a key. If the number value is too
  301. * large for an int, it will be clipped.
  302. *
  303. * @param key A key string.
  304. * @return The integer value.
  305. * @throws JSONException if the key is not found or if the value cannot
  306. * be converted to an integer.
  307.  
  308. public int getInt(String key) {
  309. Object o = get(key);
  310. return o instanceof Number ?
  311. ((Number)o).intValue() : (int)getDouble(key);
  312. } */
  313.  
  314.  
  315. /*
  316. * Get the JSONArray value associated with a key.
  317. *
  318. * @param key A key string.
  319. * @return A JSONArray which is the value.
  320. * @throws JSONException if the key is not found or
  321. * if the value is not a JSONArray.
  322.  
  323. public JSONArray getJSONArray(String key) {
  324. Object o = get(key);
  325. if (o instanceof JSONArray) {
  326. return (JSONArray)o;
  327. }
  328. throw new JSONException('JSONObject[' + quote(key) +
  329. '] is not a JSONArray.');
  330. }*/
  331.  
  332.  
  333. /* **
  334. * Get the JSONObject value associated with a key.
  335. *
  336. * @param key A key string.
  337. * @return A JSONObject which is the value.
  338. * @throws JSONException if the key is not found or
  339. * if the value is not a JSONObject.
  340.  
  341. public JSONObject getJSONObject(String key) {
  342. Object o = get(key);
  343. if (o instanceof JSONObject) {
  344. return (JSONObject)o;
  345. }
  346. throw new JSONException('JSONObject[' + quote(key) +
  347. '] is not a JSONObject.');
  348. }
  349. */
  350.  
  351. /* **
  352. * Get the long value associated with a key. If the number value is too
  353. * long for a long, it will be clipped.
  354. *
  355. * @param key A key string.
  356. * @return The long value.
  357. * @throws JSONException if the key is not found or if the value cannot
  358. * be converted to a long.
  359.  
  360. public long getLong(String key) {
  361. Object o = get(key);
  362. return o instanceof Number ?
  363. ((Number)o).longValue() : (long)getDouble(key);
  364. }
  365. */
  366.  
  367. /* **
  368. * Get an array of field names from a JSONObject.
  369. *
  370. * @return An array of field names, or null if there are no names.
  371.  
  372. public static String[] getNames(JSONObject jo) {
  373. int length = jo.length();
  374. if (length == 0) {
  375. return null;
  376. }
  377. Iterator i = jo.keys();
  378. String[] names = new String[length];
  379. int j = 0;
  380. while (i.hasNext()) {
  381. names[j] = (String)i.next();
  382. j += 1;
  383. }
  384. return names;
  385. }
  386. */
  387.  
  388. /* **
  389. * Get an array of field names from an Object.
  390. *
  391. * @return An array of field names, or null if there are no names.
  392.  
  393. public static String[] getNames(Object object) {
  394. if (object == null) {
  395. return null;
  396. }
  397. Class klass = object.getClass();
  398. Field[] fields = klass.getFields();
  399. int length = fields.length;
  400. if (length == 0) {
  401. return null;
  402. }
  403. String[] names = new String[length];
  404. for (int i = 0; i < length; i += 1) {
  405. names[i] = fields[i].getName();
  406. }
  407. return names;
  408. } */
  409.  
  410.  
  411. /* **
  412. * Get the string associated with a key.
  413. *
  414. * @param key A key string.
  415. * @return A string which is the value.
  416. * @throws JSONException if the key is not found.
  417. */
  418. public String getString(String key) {
  419. return this.data.get(key).str;
  420. }
  421.  
  422.  
  423. /* **
  424. * Determine if the JSONObject contains a specific key.
  425. * @param key A key string.
  426. * @return true if the key exists in the JSONObject.
  427. */
  428. public boolean has(String key) {
  429. return this.data.containsKey(key);
  430. }
  431.  
  432.  
  433. /* **
  434. * Determine if the value associated with the key is null or if there is
  435. * no value.
  436. * @param key A key string.
  437. * @return true if there is no value associated with the key or if
  438. * the value is the JSONObject.NULL object.
  439.  
  440. public boolean isNull(String key) {
  441. return JSONObject.NULL.equals(opt(key));
  442. }
  443. */
  444.  
  445. /* **
  446. * Get an enumeration of the keys of the JSONObject.
  447. *
  448. * @return A set of the keys.
  449. */
  450. public set<string> keys() {
  451. return this.data.keySet();
  452. }
  453.  
  454.  
  455. /* **
  456. * Get the number of keys stored in the JSONObject.
  457. *
  458. * @return The number of keys in the JSONObject.
  459. */
  460. public integer length() {
  461. return this.data.keySet().size();
  462. }
  463.  
  464.  
  465. /* **
  466. * Produce a JSONArray containing the names of the elements of this
  467. * JSONObject.
  468. * @return A JSONArray containing the key strings, or null if the JSONObject
  469. * is empty.
  470.  
  471. public JSONArray names() {
  472. JSONArray ja = new JSONArray();
  473. Iterator keys = keys();
  474. while (keys.hasNext()) {
  475. ja.put(keys.next());
  476. }
  477. return ja.length() == 0 ? null : ja;
  478. }
  479.  
  480. /* **
  481. * Produce a string from a Number.
  482. * @param n A Number
  483. * @return A String.
  484. * @ If n is a non-finite number.
  485.  
  486. public static String numberToString(Number n)
  487. {
  488. if (n == null) {
  489. throw new JSONException('Null pointer');
  490. }
  491. testValidity(n);
  492.  
  493. // Shave off trailing zeros and decimal point, if possible.
  494.  
  495. String s = n.toString();
  496. if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
  497. while (s.endsWith('0')) {
  498. s = s.substring(0, s.length() - 1);
  499. }
  500. if (s.endsWith('.')) {
  501. s = s.substring(0, s.length() - 1);
  502. }
  503. }
  504. return s;
  505. } */
  506.  
  507.  
  508. /* **
  509. * Get an optional value associated with a key.
  510. * @param key A key string.
  511. * @return An object which is the value, or null if there is no value.
  512. */
  513. public Object opt(String key) {
  514. return key == null ? null : this.get(key);
  515. }
  516.  
  517.  
  518. /* **
  519. * Get an optional boolean associated with a key.
  520. * It returns false if there is no such key, or if the value is not
  521. * true or the String 'true'.
  522. *
  523. * @param key A key string.
  524. * @return The truth.
  525. */
  526. public boolean optBoolean(String key) {
  527. return optBoolean(key, false);
  528. }
  529.  
  530.  
  531. /* **
  532. * Get an optional boolean associated with a key.
  533. * It returns the defaultValue if there is no such key, or if it is not
  534. * a Boolean or the String 'true' or 'false' (case insensitive).
  535. *
  536. * @param key A key string.
  537. * @param defaultValue The default.
  538. * @return The truth.
  539. */
  540. public boolean optBoolean(String key, boolean defaultValue) {
  541. try {
  542. return getBoolean(key);
  543. } catch (Exception e) {
  544. return defaultValue;
  545. }
  546. }
  547.  
  548.  
  549. /* **
  550. * Put a key/value pair in the JSONObject, where the value will be a
  551. * JSONArray which is produced from a Collection.
  552. * @param key A key string.
  553. * @param value A Collection value.
  554. * @return this.
  555. * @
  556.  
  557. public JSONObject put(String key, Collection value) {
  558. put(key, new JSONArray(value));
  559. return this;
  560. }*/
  561.  
  562.  
  563. /* **
  564. * Get an optional double associated with a key,
  565. * or NaN if there is no such key or if its value is not a number.
  566. * If the value is a string, an attempt will be made to evaluate it as
  567. * a number.
  568. *
  569. * @param key A string which is the key.
  570. * @return An object which is the value.
  571.  
  572. public double optDouble(String key) {
  573. return optDouble(key, Double.NaN);
  574. } */
  575.  
  576.  
  577. /* **
  578. * Get an optional double associated with a key, or the
  579. * defaultValue if there is no such key or if its value is not a number.
  580. * If the value is a string, an attempt will be made to evaluate it as
  581. * a number.
  582. *
  583. * @param key A key string.
  584. * @param defaultValue The default.
  585. * @return An object which is the value.
  586.  
  587. public double optDouble(String key, double defaultValue) {
  588. try {
  589. Object o = opt(key);
  590. return o instanceof Number ? ((Number)o).doubleValue() :
  591. new Double((String)o).doubleValue();
  592. } catch (Exception e) {
  593. return defaultValue;
  594. }
  595. } */
  596.  
  597.  
  598. /* **
  599. * Get an optional int value associated with a key,
  600. * or zero if there is no such key or if the value is not a number.
  601. * If the value is a string, an attempt will be made to evaluate it as
  602. * a number.
  603. *
  604. * @param key A key string.
  605. * @return An object which is the value.
  606.  
  607. public int optInt(String key) {
  608. return optInt(key, 0);
  609. } */
  610.  
  611.  
  612. /* **
  613. * Get an optional int value associated with a key,
  614. * or the default if there is no such key or if the value is not a number.
  615. * If the value is a string, an attempt will be made to evaluate it as
  616. * a number.
  617. *
  618. * @param key A key string.
  619. * @param defaultValue The default.
  620. * @return An object which is the value.
  621.  
  622. public int optInt(String key, int defaultValue) {
  623. try {
  624. return getInt(key);
  625. } catch (Exception e) {
  626. return defaultValue;
  627. }
  628. }*/
  629.  
  630.  
  631. /* **
  632. * Get an optional JSONArray associated with a key.
  633. * It returns null if there is no such key, or if its value is not a
  634. * JSONArray.
  635. *
  636. * @param key A key string.
  637. * @return A JSONArray which is the value.
  638.  
  639. public JSONArray optJSONArray(String key) {
  640. Object o = opt(key);
  641. return o instanceof JSONArray ? (JSONArray)o : null;
  642. }*/
  643.  
  644.  
  645. /* **
  646. * Get an optional JSONObject associated with a key.
  647. * It returns null if there is no such key, or if its value is not a
  648. * JSONObject.
  649. *
  650. * @param key A key string.
  651. * @return A JSONObject which is the value.
  652.  
  653. public JSONObject optJSONObject(String key) {
  654. Object o = opt(key);
  655. return o instanceof JSONObject ? (JSONObject)o : null;
  656. }
  657. */
  658.  
  659. /* **
  660. * Get an optional long value associated with a key,
  661. * or zero if there is no such key or if the value is not a number.
  662. * If the value is a string, an attempt will be made to evaluate it as
  663. * a number.
  664. *
  665. * @param key A key string.
  666. * @return An object which is the value.
  667.  
  668. public long optLong(String key) {
  669. return optLong(key, 0);
  670. }
  671. */
  672.  
  673. /* **
  674. * Get an optional long value associated with a key,
  675. * or the default if there is no such key or if the value is not a number.
  676. * If the value is a string, an attempt will be made to evaluate it as
  677. * a number.
  678. *
  679. * @param key A key string.
  680. * @param defaultValue The default.
  681. * @return An object which is the value.
  682.  
  683. public long optLong(String key, long defaultValue) {
  684. try {
  685. return getLong(key);
  686. } catch (Exception e) {
  687. return defaultValue;
  688. }
  689. }*/
  690.  
  691.  
  692. /* **
  693. * Get an optional string associated with a key.
  694. * It returns an empty string if there is no such key. If the value is not
  695. * a string and is not null, then it is coverted to a string.
  696. *
  697. * @param key A key string.
  698. * @return A string which is the value.
  699.  
  700. public String optString(String key) {
  701. return optString(key, '');
  702. }
  703. */
  704.  
  705. /* **
  706. * Get an optional string associated with a key.
  707. * It returns the defaultValue if there is no such key.
  708. *
  709. * @param key A key string.
  710. * @param defaultValue The default.
  711. * @return A string which is the value.
  712.  
  713. public String optString(String key, String defaultValue) {
  714. Object o = opt(key);
  715. return o != null ? o.toString() : defaultValue;
  716. } */
  717.  
  718.  
  719. /* **
  720. * Put a key/boolean pair in the JSONObject.
  721. *
  722. * @param key A key string.
  723. * @param value A boolean which is the value.
  724. * @return this.
  725. * @ If the key is null.
  726.  
  727. public JSONObject put(String key, boolean value) {
  728. put(key, value ? true : FALSE);
  729. return this;
  730. } */
  731.  
  732.  
  733. /* **
  734. * Put a key/double pair in the JSONObject.
  735. *
  736. * @param key A key string.
  737. * @param value A double which is the value.
  738. * @return this.
  739. * @ If the key is null or if the number is invalid.
  740.  
  741. public JSONObject put(String key, double value) {
  742. put(key, new Double(value));
  743. return this;
  744. } */
  745.  
  746.  
  747. /* **
  748. * Put a key/int pair in the JSONObject.
  749. *
  750. * @param key A key string.
  751. * @param value An int which is the value.
  752. * @return this.
  753. * @ If the key is null.
  754.  
  755. public JSONObject put(String key, int value) {
  756. put(key, new Integer(value));
  757. return this;
  758. }
  759. */
  760.  
  761. /* **
  762. * Put a key/value pair in the JSONObject, but only if the
  763. * key and the value are both non-null.
  764. * @param key A key string.
  765. * @param value An object which is the value. It should be of one of these
  766. * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
  767. * or the JSONObject.NULL object.
  768. * @return this.
  769. * @ If the value is a non-finite number.
  770. */
  771. public JSONObject putOpt(String key, value value) {
  772. if (key != null && value != null) {
  773. data.put(key, value);
  774. }
  775. return this;
  776. }
  777.  
  778.  
  779. /*
  780. * Produce a string in double quotes with backslash sequences in all the
  781. * right places. A backslash will be inserted within </, allowing JSON
  782. * text to be delivered in HTML. In JSON text, a string cannot contain a
  783. * control character or an unescaped quote or backslash.
  784. * @param string A String
  785. * @return A String correctly formatted for insertion in a JSON text.
  786.  
  787. static public String quote(String string) {
  788. return '';
  789.  
  790. if (string == null || string.length() == 0) {
  791. return '\'\'';
  792. }
  793.  
  794. char b;
  795. char c = 0;
  796. int i;
  797. int len = string.length();
  798. StringBuffer sb = new StringBuffer(len + 4);
  799. String t;
  800.  
  801. sb.append('"');
  802. for (i = 0; i < len; i += 1) {
  803. b = c;
  804. c = string.charAt(i);
  805. switch (c) {
  806. case '\\':
  807. case '"':
  808. sb.append('\\');
  809. sb.append(c);
  810. break;
  811. case '/':
  812. if (b == '<') {
  813. sb.append('\\');
  814. }
  815. sb.append(c);
  816. break;
  817. case '\b':
  818. sb.append("\\b");
  819. break;
  820. case '\t':
  821. sb.append("\\t");
  822. break;
  823. case '\n':
  824. sb.append("\\n");
  825. break;
  826. case '\f':
  827. sb.append("\\f");
  828. break;
  829. case '\r':
  830. sb.append("\\r");
  831. break;
  832. default:
  833. if (c < ' ' || (c >= '\u0080' && c < '\u00a0') ||
  834. (c >= '\u2000' && c < '\u2100')) {
  835. t = "000" + Integer.toHexString(c);
  836. sb.append("\\u" + t.substring(t.length() - 4));
  837. } else {
  838. sb.append(c);
  839. }
  840. }
  841. }
  842. sb.append('"');
  843. return sb.toString();
  844. }*/
  845.  
  846.  
  847. /* **
  848. * Make a JSON text of this JSONObject. For compactness, no whitespace
  849. * is added. If this would not result in a syntactically correct JSON text,
  850. * then null will be returned instead.
  851. * <p>
  852. * Warning: This method assumes that the data structure is acyclical.
  853. *
  854. * @return a printable, displayable, portable, transmittable
  855. * representation of the object, beginning
  856. * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  857. * with <code>}</code>&nbsp;<small>(right brace)</small>.
  858.  
  859. public String toString() {
  860. try {
  861. Iterator keys = keys();
  862. StringBuffer sb = new StringBuffer('{');
  863.  
  864. while (keys.hasNext()) {
  865. if (sb.length() > 1) {
  866. sb.append(',');
  867. }
  868. Object o = keys.next();
  869. sb.append(quote(o.toString()));
  870. sb.append(':');
  871. sb.append(valueToString(this.map.get(o)));
  872. }
  873. sb.append('}');
  874. return sb.toString();
  875. } catch (Exception e) {
  876. return null;
  877. }
  878. } */
  879.  
  880.  
  881.  
  882.  
  883. /* **
  884. * Make a prettyprinted JSON text of this JSONObject.
  885. * <p>
  886. * Warning: This method assumes that the data structure is acyclical.
  887. * @param indentFactor The number of spaces to add to each level of
  888. * indentation.
  889. * @param indent The indentation of the top level.
  890. * @return a printable, displayable, transmittable
  891. * representation of the object, beginning
  892. * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  893. * with <code>}</code>&nbsp;<small>(right brace)</small>.
  894. * @ If the object contains an invalid number.
  895.  
  896. String toString(int indentFactor, int indent) {
  897. int j;
  898. int n = length();
  899. if (n == 0) {
  900. return '{}';
  901. }
  902. Iterator keys = sortedKeys();
  903. StringBuffer sb = new StringBuffer('{');
  904. int newindent = indent + indentFactor;
  905. Object o;
  906. if (n == 1) {
  907. o = keys.next();
  908. sb.append(quote(o.toString()));
  909. sb.append(': ');
  910. sb.append(valueToString(this.map.get(o), indentFactor,
  911. indent));
  912. } else {
  913. while (keys.hasNext()) {
  914. o = keys.next();
  915. if (sb.length() > 1) {
  916. sb.append(',\n');
  917. } else {
  918. sb.append('\n');
  919. }
  920. for (j = 0; j < newindent; j += 1) {
  921. sb.append(' ');
  922. }
  923. sb.append(quote(o.toString()));
  924. sb.append(': ');
  925. sb.append(valueToString(this.map.get(o), indentFactor,
  926. newindent));
  927. }
  928. if (sb.length() > 1) {
  929. sb.append('\n');
  930. for (j = 0; j < indent; j += 1) {
  931. sb.append(' ');
  932. }
  933. }
  934. }
  935. sb.append('}');
  936. return sb.toString();
  937. }
  938. */
  939.  
  940. /* **
  941. * valueToString
  942. * Make a JSON text of an Object value. The method is required to produce a strictly
  943. * conforming text. If the object does not contain a toJSONString
  944. * method (which is the most common case), then a text will be
  945. * produced by other means. the
  946. * value's toString method will be called, and the result will be quoted.
  947. *
  948. * <p>
  949. * Warning: This method assumes that the data structure is acyclical.
  950. * @param value The value to be serialized.
  951. * @return a printable, displayable, transmittable
  952. * representation of the object, beginning
  953. * with <code>{</code>&nbsp;<small>(left brace)</small> and ending
  954. * with <code>}</code>&nbsp;<small>(right brace)</small>.
  955. * @ If the value is or contains an invalid number.
  956. */
  957. public String valueToString() {
  958. string ret = '{';
  959. for ( string key: this.keys() ) {
  960. ret += key + ': ' + this.getvalue(key).valueToString() + ',';
  961. }
  962. return ret.substring(0,ret.length()-1) + '}';
  963. }
  964.  
  965.  
  966.  
  967. public class JSONException extends Exception {}
  968.  
  969.  
  970. public class JSONTokener {
  971. /*
  972. * A JSONTokener takes a source string and extracts characters and tokens from
  973. * it. It is used by the JSONObject and JSONArray constructors to parse
  974. * JSON source strings.
  975. * @author JSON.org
  976. * @version 3
  977. */
  978.  
  979. private integer index;
  980. private string reader;
  981. private string lastChar;
  982. private boolean useLastChar;
  983.  
  984. /*
  985. * Construct a JSONTokener from a string.
  986. *
  987. * @param s A source string.
  988. */
  989. public JSONTokener(String s) {
  990. this.useLastChar = false;
  991. this.index = 0;
  992. this.reader = s;
  993. }
  994.  
  995. /*
  996. * Back up one character. This provides a sort of lookahead capability,
  997. * so that you can test for a digit or letter before attempting to parse
  998. * the next number or identifier.
  999. */
  1000. public void back() {
  1001. if (useLastChar || index <= 0) {
  1002. throw new JSONException('Stepping back two steps is not supported');
  1003. }
  1004. index -= 1;
  1005. useLastChar = true;
  1006. }
  1007.  
  1008.  
  1009. /*
  1010. * Determine if the source string still contains characters that next()
  1011. * can consume.
  1012. * @return true if not yet at the end of the source.
  1013. */
  1014. public boolean more() {
  1015. String nextChar = next();
  1016. if (nextChar == null) {
  1017. return false;
  1018. }
  1019. back();
  1020. return true;
  1021. }
  1022.  
  1023. string read( string reader) {
  1024. if ( index+1 > reader.length() ) return null;
  1025. return reader.substring(index,index+1);
  1026. }
  1027.  
  1028. /*
  1029. * Get the next character in the source string.
  1030. *
  1031. * @return The next character, or 0 if past the end of the source string.
  1032. */
  1033. public String next() {
  1034. if (this.useLastChar) {
  1035. this.useLastChar = false;
  1036. if (this.lastChar != null) {
  1037. this.index += 1;
  1038. }
  1039. return this.lastChar;
  1040. }
  1041. string c;
  1042. try {
  1043. c = read(reader);
  1044. } catch (exception exc) {
  1045. throw new JSONException(exc);
  1046. }
  1047.  
  1048. if (c == null) { // End of stream
  1049. this.lastChar = null;
  1050. return null;
  1051. }
  1052. this.index += 1;
  1053. this.lastChar = (String) c;
  1054. return this.lastChar;
  1055. }
  1056.  
  1057.  
  1058. /*
  1059. * Consume the next character, and check that it matches a specified
  1060. * character.
  1061. * @param c The character to match.
  1062. * @return The character.
  1063. * @throws JSONException if the character does not match.
  1064. */
  1065. public String next(String c) {
  1066. String n = next();
  1067. if (n != c) {
  1068. throw new JSONException('Expected ' + c + ' and instead saw ' + n );
  1069. }
  1070. return n;
  1071. }
  1072.  
  1073.  
  1074. /*
  1075. * Get the next n characters.
  1076. *
  1077. * @param n The number of characters to take.
  1078. * @return A string of n characters.
  1079. * @throws JSONException
  1080. * Substring bounds error if there are not
  1081. * n characters remaining in the source string.
  1082. */
  1083. public String next(integer n) {
  1084. if (n == 0) {
  1085. return '';
  1086. }
  1087.  
  1088. String buffer = '';
  1089. integer pos = 0;
  1090.  
  1091. if (this.useLastChar) {
  1092. this.useLastChar = false;
  1093. buffer = this.lastChar;
  1094. pos = 1;
  1095. }
  1096.  
  1097. try {
  1098. buffer = buffer + reader.substring(index, index+n);
  1099. pos += n;
  1100. } catch (Exception exc) {
  1101. throw new JSONException(exc.getMessage());
  1102. }
  1103. this.index += pos;
  1104.  
  1105. if (pos < n) {
  1106. throw new JSONException('Substring bounds error');
  1107. }
  1108.  
  1109. this.lastChar = buffer.substring( buffer.length()-1 );
  1110. return buffer;
  1111. }
  1112.  
  1113.  
  1114. /*
  1115. * Get the next char in the string, skipping whitespace
  1116. * and comments (slashslash, slashstar, and hash).
  1117. * @throws JSONException
  1118. * @return A character, or 0 if there are no more characters.
  1119. */
  1120. public string nextClean() {
  1121. for (;;) {
  1122. string c = next();
  1123. //system.debug( 'next clean '+c);
  1124.  
  1125. if (c == '/') {
  1126. string n = next();
  1127. //system.debug( 'next clean '+n);
  1128. if ( n == '/' ) {
  1129. do {
  1130. c = next();
  1131. } while (c != '\n' && c != '\r' && c != null);
  1132.  
  1133. }
  1134. else
  1135. if (n == '*') {
  1136. for (;;) {
  1137. c = next();
  1138. if (c == null) {
  1139. throw new JSONException('Unclosed comment');
  1140. }
  1141. if (c == '*') {
  1142. if (next() == '/') {
  1143. break;
  1144. }
  1145. back();
  1146. }
  1147. }
  1148. } else {
  1149. back();
  1150. return '/';
  1151. }
  1152. } else if (c == '#') {
  1153. do {
  1154. c = next();
  1155. } while (c != '\n' && c != '\r' && c != null);
  1156. }
  1157. if (c == null || c > ' ') {
  1158. //system.debug( 'nextClean returns :'+c);
  1159. return c;
  1160. }
  1161. }
  1162. return null;
  1163. }
  1164.  
  1165. /*
  1166. * Return the characters up to the next close quote character.
  1167. * Backslash processing is done. The formal JSON format does not
  1168. * allow strings in single quotes, but an implementation is allowed to
  1169. * accept them.
  1170. * @param quote The quoting character, either
  1171. * <code>"</code>&nbsp;<small>(double quote)</small> or
  1172. * <code>'</code>&nbsp;<small>(single quote)</small>.
  1173. * @return A String.
  1174. * @throws JSONException Unterminated string.
  1175. */
  1176. public String nextString(string quote) {
  1177. //system.debug( 'nextString ' +quote);
  1178. string c;
  1179. string sb = '';
  1180. for (;;) {
  1181. c = next(); //system.debug(c);
  1182. //switch (c) {
  1183. if ( c == null || c == '\n' || c == '\r') {
  1184. throw new JSONException('Unterminated string');
  1185. }
  1186. /*
  1187. if ( c == '/' ) {
  1188. c = next();
  1189. if ( c == 'n') { sb += '\n'; continue; }
  1190. }
  1191.  
  1192. if ( c == '/' ) {
  1193. c = next();
  1194. switch (c) {
  1195. case 'b':
  1196. sb.append('\b');
  1197. break;
  1198. case 't':
  1199. sb.append('\t');
  1200. break;
  1201. case 'n':
  1202. sb.append('\n');
  1203. break;
  1204. case 'f':
  1205. sb.append('\f');
  1206. break;
  1207. case 'r':
  1208. sb.append('\r');
  1209. break;
  1210. case 'u':
  1211. sb.append((char)Integer.parseInt(next(4), 16));
  1212. break;
  1213. case 'x' :
  1214. sb.append((char) Integer.parseInt(next(2), 16));
  1215. break;
  1216. default:
  1217. sb.append(c);
  1218. }
  1219. break;
  1220. */
  1221.  
  1222. if (c == quote) {
  1223. // system.debug( 'nextString returns :'+sb);
  1224. return sb;
  1225. }
  1226. sb = sb + c;
  1227.  
  1228. }
  1229. return '';
  1230. }
  1231.  
  1232.  
  1233. /**
  1234. * Get the text up but not including the specified character or the
  1235. * end of line, whichever comes first.
  1236. * @param d A delimiter character.
  1237. * @return A string.
  1238. */
  1239. public String nextTo(string d) {
  1240. string sb = '';
  1241. for (;;) {
  1242. string c = next();
  1243. if (c == d || c == null || c == '\n' || c == '\r') {
  1244. if (c != null) {
  1245. back();
  1246. }
  1247. return sb.trim();
  1248. }
  1249. sb = sb + c;
  1250. }
  1251. return '';
  1252. }
  1253.  
  1254.  
  1255. /**
  1256. * Get the text up but not including one of the specified delimiter
  1257. * characters or the end of line, whichever comes first.
  1258. * @param delimiters A set of delimiter characters.
  1259. * @return A string, trimmed.
  1260.  
  1261. public String nextTod(String delimiters) {
  1262. string c;
  1263. String sb = '';
  1264. for (;;) {
  1265. c = next();
  1266. if (delimiters.indexOf(c) >= 0 || c == null ||
  1267. c == '\n' || c == '\r') {
  1268. if (c != null) {
  1269. back();
  1270. }
  1271. return sb.trim();
  1272. }
  1273. sb = sb + c;
  1274. }
  1275. return '';
  1276. } */
  1277.  
  1278.  
  1279. /*
  1280. * Get the next value. The value can be a Boolean, Double, Integer,
  1281. * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
  1282. * @throws JSONException If syntax error.
  1283. *
  1284. * @return An object.
  1285. */
  1286.  
  1287.  
  1288. public value nextValue() {
  1289.  
  1290. string c = nextClean();
  1291. // system.debug( 'nextValue ' +c);
  1292. String s;
  1293.  
  1294. if ( c == '"' || c == '\'' ) {
  1295. return new value( nextString(c) );
  1296. }
  1297. if ( c == '{' ) {
  1298. back();
  1299. return new value( new JSONObject(this) );
  1300. }
  1301. if ( c == '[' || c == '(') {
  1302. back();
  1303. return new value( JSONArray(this) );
  1304. }
  1305.  
  1306. /*
  1307. * Handle unquoted text. This could be the values true, false, or
  1308. * null, or it can be a number. An implementation (such as this one)
  1309. * is allowed to also accept non-standard forms.
  1310. *
  1311. * Accumulate characters until we reach the end of the text or a
  1312. * formatting character.
  1313. */
  1314.  
  1315. String sb = '';
  1316. string b = c;
  1317. while (c >= ' ' && '),:]}/\\\"[{;=#'.indexOf(c) < 0) {
  1318. sb = sb + c;
  1319. //system.debug(sb);
  1320. c = next();
  1321.  
  1322. }
  1323. back();
  1324.  
  1325. /*
  1326. * If it is true, false, or null, return the proper value.
  1327. */
  1328.  
  1329. s = sb.trim();
  1330. if (s.equals('')) {
  1331. throw new JSONException ('Missing value');
  1332. }
  1333. if (s.equalsIgnoreCase('true')) {
  1334.  
  1335. return new value(true);
  1336. }
  1337. if (s.equalsIgnoreCase('false')) {
  1338. return new value( false);
  1339. }
  1340. if (s.equalsIgnoreCase('null')) {
  1341. return new value();
  1342. }
  1343.  
  1344. /*
  1345. * If it might be a number, try converting it. We support the 0- and 0x-
  1346. * conventions. If a number cannot be produced, then the value will just
  1347. * be a string. Note that the 0-, 0x-, plus, and implied string
  1348. * conventions are non-standard. A JSON parser is free to accept
  1349. * non-JSON forms as long as it accepts all correct JSON forms.
  1350. */
  1351.  
  1352. if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
  1353. if (b == '0') {
  1354. if (s.length() > 2 &&
  1355. (s.substring(1,2) == 'x' || s.substring(1,2) == 'X')) {
  1356. try {
  1357. return new value( Integer.valueof(s.substring(2)) );
  1358. } catch (Exception e) {
  1359. /* Ignore the error */
  1360. }
  1361. } else {
  1362. try {
  1363. return new value( Integer.valueof(s) );
  1364. } catch (Exception e) {
  1365. /* Ignore the error */
  1366. }
  1367. }
  1368. }
  1369. try {
  1370. return new value( Integer.valueof(s) );
  1371. } catch (Exception e) {
  1372. /* try {
  1373. return new Long(s);
  1374. } catch (Exception f) {
  1375. try {
  1376. return new Double(s);
  1377. } catch (Exception g) {
  1378. return s;
  1379. }
  1380. }
  1381. */
  1382. }
  1383. }
  1384. return new value( s );
  1385. }
  1386.  
  1387.  
  1388. /**
  1389. * Skip characters until the next character is the requested character.
  1390. * If the requested character is not found, no characters are skipped.
  1391. * @param to A character to skip to.
  1392. * @return The requested character, or zero if the requested character
  1393. * is not found.
  1394. */
  1395. public string skipTo(string to) {
  1396. string c;
  1397. try {
  1398. integer startIndex = this.index;
  1399. //reader.mark(Integer.MAX_VALUE);
  1400. do {
  1401. c = next();
  1402. if (c == null) {
  1403. // reader.reset();
  1404. this.index = startIndex;
  1405. return c;
  1406. }
  1407. } while (c != to);
  1408. } catch (Exception exc) {
  1409. throw new JSONException(exc);
  1410. }
  1411.  
  1412. back();
  1413. return c;
  1414. }
  1415.  
  1416. /*
  1417. * Make a printable string of this JSONTokener.
  1418. *
  1419. * @return ' at character [this.index]'
  1420. public String toString() {
  1421. return ' at character ' + index;
  1422. }
  1423. */
  1424.  
  1425. } // end of tokener (sub) class
  1426.  
  1427. /*
  1428. * Construct a JSONArray from a JSONTokener.
  1429. * @param x A JSONTokener
  1430. * @throws JSONException If there is a syntax error.
  1431. */
  1432. public static list<value> JSONArray(JSONTokener x) {
  1433. //this();
  1434. list<value> myArrayList = new list<value>();
  1435. string c = x.nextClean();
  1436. string q;
  1437. if (c == '[') {
  1438. q = ']';
  1439. } else if (c == '(') {
  1440. q = ')';
  1441. } else {
  1442. throw new JSONException('A JSONArray text must start with [');
  1443. }
  1444. if (x.nextClean() == ']') {
  1445. return myArrayList;
  1446. }
  1447. x.back();
  1448. for (;;) {
  1449. if (x.nextClean() == ',') {
  1450. x.back();
  1451. myArrayList.add(null);
  1452. } else {
  1453. x.back();
  1454. myArrayList.add(x.nextValue());
  1455. }
  1456. c = x.nextClean();
  1457. //switch (c) {
  1458. if ( c == ';' || c == ',') {
  1459. if (x.nextClean() == ']') {
  1460. return myArrayList;
  1461. }
  1462. x.back();
  1463.  
  1464. } else if ( c == ']' || c == ')') {
  1465. if (q != c) {
  1466. throw new JSONException('Expected a >' + q + '<');
  1467. }
  1468. return myArrayList;
  1469. } else {
  1470. throw new JSONException('Expected a , or ]');
  1471. }
  1472. }
  1473. return null;// not reached
  1474. }
  1475.  
  1476.  
  1477. /* **************************
  1478. * TEST Methods to achieve required code coverage
  1479. * many of these could be improved by using assert() instead of debug()
  1480. */
  1481. public static testmethod void test_tokener_nl() {
  1482. //add a new line by inserting /n
  1483. JsonObject.JsonTokener tkr = new JsonTokener(
  1484. 'quoted string foo"');
  1485. system.debug( 'next string is >'+tkr.nextString('"') );
  1486. }
  1487. public static testmethod void test_tokener() {
  1488. JsonObject.JsonTokener tkr = new JsonTokener('//ff \n{}');
  1489. tkr.nextClean();
  1490. tkr = new JsonTokener('/*fff*/\n{}');
  1491. tkr.nextClean();
  1492. tkr = new JsonTokener('#ff*\n{}');
  1493. tkr.nextClean();
  1494. tkr = new JsonTokener('/**ff \n{}');
  1495. try { tkr.nextClean(); } catch(exception ex) {
  1496. system.debug( ' expected >'+ex.getMessage() + '<' );
  1497. system.assert( ex.getMessage() == 'Unclosed comment');
  1498. }
  1499. }
  1500. public static testmethod void test_parsing() { JSONObject jj; JsonObject.JsonTokener tkr;
  1501. string simple = '{"translatedText": "Ciao mondo" }';
  1502. string bool_simple = '{"responseBoolean" : true }';
  1503. string nsimple = '{"responseData" : {"translatedText": "Ciao mondo" }, "responseDetails": null, "responseStatus": 200 }';
  1504.  
  1505. // three methods of constructing an object
  1506. system.debug( jsonobject.instance( bool_simple ) );
  1507. system.debug( new jsonobject( bool_simple ) );
  1508. system.debug( new JSONObject( new JsonTokener(simple) ) );
  1509.  
  1510. tkr = new JsonTokener(nsimple);
  1511. system.debug( tkr.more() );
  1512. system.debug( tkr.next(1) );
  1513. system.assert( tkr.next(0) == '' );
  1514.  
  1515. try { tkr.next(10000); } catch(exception ex) {
  1516. system.debug( ' expected >'+ex.getMessage() + '<' );
  1517. system.assert( ex.getMessage() == 'Ending position out of bounds: 10002');
  1518. }
  1519.  
  1520. system.debug( tkr.next('r') );
  1521.  
  1522. try { tkr.next('z'); } catch(exception ex) {
  1523. system.debug( ' expected >'+ex.getMessage() + '<' );
  1524. system.assert( ex.getMessage() == 'Expected z and instead saw e');
  1525. }
  1526.  
  1527. system.debug( tkr.nextTo('e') );
  1528. system.debug( tkr.skipTo('p') );
  1529. system.debug( tkr.skipTo('z') );
  1530.  
  1531. tkr = new JsonTokener(nsimple);
  1532. jj = new JSONObject( tkr);
  1533.  
  1534. system.debug( jj.data );
  1535. system.debug( jj.data.keySet() );
  1536.  
  1537. system.debug( 'response status ' + jj.data.get('responseStatus') );
  1538. system.debug( 'response status ' + jj.get('responseStatus') );
  1539. system.debug( 'response details ' + jj.get('responseDetails') );
  1540.  
  1541. system.debug( jj.getString('responseDetails') );
  1542. system.assert( jj.getString('responseDetails') == null ,'expected null ');
  1543.  
  1544. system.debug('value '+ jj.getValue('responseData') );
  1545.  
  1546. value v = jj.data.get('responseData');
  1547. system.debug( jj.getString('responseDetails') );
  1548. system.debug( 'response data is '+ v.obj);
  1549.  
  1550. //system.assert( v.obj.valu != null);
  1551. system.debug( jj.data.keySet() );
  1552.  
  1553.  
  1554. nsimple = '{"responseString" : "foo" }';
  1555. tkr = new JsonTokener(nsimple);
  1556. jj = new JSONObject( tkr);
  1557. system.debug( jj.get('responseString') );
  1558.  
  1559. nsimple = '{"responseBoolean" : true }';
  1560. tkr = new JsonTokener(nsimple);
  1561. jj = new JSONObject( tkr);
  1562. system.debug( jj.getValue('responseBoolean') );
  1563. system.debug( jj.optBoolean('responseBoolean') );
  1564.  
  1565.  
  1566. try {
  1567. system.debug ( new JSONObject ( new JSONTokener( 'sdfsdf' ) ) );
  1568. } catch(exception ex) {
  1569. system.debug( ' expected >'+ex.getMessage() + '<' );
  1570. system.assert( ex.getMessage() == 'A JSONObject text must begin with {');
  1571. }
  1572.  
  1573. try {
  1574. system.debug ( new JSONObject ( new JSONTokener( '{"sdfsdf": true' ) ) );
  1575. } catch(exception ex) {
  1576. system.debug( ' expected >'+ex.getMessage() + '<' );
  1577. system.assert( ex.getMessage() == 'Expected a , or }');
  1578. }
  1579.  
  1580. try {
  1581. system.debug ( new JSONObject ( new JSONTokener( '{"sdfsdf' ) ) );
  1582. } catch(exception ex) {
  1583. system.debug( ' expected >'+ex.getMessage() + '<' );
  1584. system.assert( ex.getMessage() == 'Unterminated string');
  1585. }
  1586.  
  1587. try {
  1588. system.debug ( new JSONObject ( new JSONTokener( '{"sdfsdf": 0x009.9 }' ) ) );
  1589. } catch(exception ex) {
  1590. system.debug( ' expected >'+ex.getMessage() + '<' );
  1591. system.assert( ex.getMessage() == 'Invalid integer: 009.9');
  1592. }
  1593.  
  1594.  
  1595. system.assert ( new JSONObject ( new JSONTokener( '{"sdfsdf": 009 }' ) ).getValue('sdfsdf').num == 9 );
  1596.  
  1597. system.debug ( new JSONObject ( new JSONTokener( '{"foo": 009 }' ) ).get('foo') == 9 );
  1598.  
  1599. // array testing
  1600. system.debug ( JSONObject.jsonarray ( new JSONTokener( '[1,2,3]' ) ) );
  1601. system.debug ( JSONObject.jsonarray ( new JSONTokener( '[1,2,3,]' ) ) );
  1602. system.debug ( JSONObject.jsonarray ( new JSONTokener( '[]' ) ) );
  1603. system.debug ( JSONObject.jsonarray ( new JSONTokener( '(1,2,3 )' ) ) );
  1604.  
  1605. try {
  1606. system.debug ( JSONObject.jsonarray ( new JSONTokener( '(1,2,3 ]' ) ) );
  1607. } catch(exception ex) {
  1608. system.debug( ' expected >'+ex.getMessage() + '<' );
  1609. system.assert( ex.getMessage() == 'Expected a >)<');
  1610. }
  1611.  
  1612. try {
  1613. system.debug ( JSONObject.jsonarray ( new JSONTokener( '1,2,3 ]' ) ) );
  1614. } catch(exception ex) {
  1615. system.debug( ' expected >'+ex.getMessage() + '<' );
  1616. system.assert( ex.getMessage() == 'A JSONArray text must start with [');
  1617. }
  1618.  
  1619. try {
  1620. system.debug ( jj.get('notfound') );
  1621. } catch(exception ex) {
  1622. system.debug( ' expected >'+ex.getMessage() + '<' );
  1623. system.assert( ex.getMessage() == 'JSONObject[notfound] not found.');
  1624. }
  1625.  
  1626. system.assert( jj.keys() != null );
  1627. system.assert( jj.length() > 0 );
  1628. system.assert( jj.opt('responseBoolean') != null );
  1629. system.assert( jj.has( 'responseBoolean') );
  1630. try {
  1631. system.debug ( jj.getBoolean('notfound') );
  1632. } catch(exception ex) {
  1633. system.debug( ' expected >'+ex.getMessage() + '<' );
  1634. system.assert( ex.getMessage() == 'JSONObject[notfound] not found.');
  1635. }
  1636. }
  1637.  
  1638.  
  1639. }

Report this snippet  

You need to login to post a comment.