Java IRC bot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JSONWriter.java 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. package org.json;
  2. import java.io.IOException;
  3. import java.io.Writer;
  4. /*
  5. Copyright (c) 2006 JSON.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in all
  13. copies or substantial portions of the Software.
  14. The Software shall be used for Good, not Evil.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. */
  23. /**
  24. * JSONWriter provides a quick and convenient way of producing JSON text.
  25. * The texts produced strictly conform to JSON syntax rules. No whitespace is
  26. * added, so the results are ready for transmission or storage. Each instance of
  27. * JSONWriter can produce one JSON text.
  28. * <p>
  29. * A JSONWriter instance provides a <code>value</code> method for appending
  30. * values to the
  31. * text, and a <code>key</code>
  32. * method for adding keys before values in objects. There are <code>array</code>
  33. * and <code>endArray</code> methods that make and bound array values, and
  34. * <code>object</code> and <code>endObject</code> methods which make and bound
  35. * object values. All of these methods return the JSONWriter instance,
  36. * permitting a cascade style. For example, <pre>
  37. * new JSONWriter(myWriter)
  38. * .object()
  39. * .key("JSON")
  40. * .value("Hello, World!")
  41. * .endObject();</pre> which writes <pre>
  42. * {"JSON":"Hello, World!"}</pre>
  43. * <p>
  44. * The first method called must be <code>array</code> or <code>object</code>.
  45. * There are no methods for adding commas or colons. JSONWriter adds them for
  46. * you. Objects and arrays can be nested up to 20 levels deep.
  47. * <p>
  48. * This can sometimes be easier than using a JSONObject to build a string.
  49. * @author JSON.org
  50. * @version 2008-09-18
  51. */
  52. public class JSONWriter {
  53. private static final int maxdepth = 20;
  54. /**
  55. * The comma flag determines if a comma should be output before the next
  56. * value.
  57. */
  58. private boolean comma;
  59. /**
  60. * The current mode. Values:
  61. * 'a' (array),
  62. * 'd' (done),
  63. * 'i' (initial),
  64. * 'k' (key),
  65. * 'o' (object).
  66. */
  67. protected char mode;
  68. /**
  69. * The object/array stack.
  70. */
  71. private JSONObject stack[];
  72. /**
  73. * The stack top index. A value of 0 indicates that the stack is empty.
  74. */
  75. private int top;
  76. /**
  77. * The writer that will receive the output.
  78. */
  79. protected Writer writer;
  80. /**
  81. * Make a fresh JSONWriter. It can be used to build one JSON text.
  82. */
  83. public JSONWriter(Writer w) {
  84. this.comma = false;
  85. this.mode = 'i';
  86. this.stack = new JSONObject[maxdepth];
  87. this.top = 0;
  88. this.writer = w;
  89. }
  90. /**
  91. * Append a value.
  92. * @param s A string value.
  93. * @return this
  94. * @throws JSONException If the value is out of sequence.
  95. */
  96. private JSONWriter append(String s) throws JSONException {
  97. if (s == null) {
  98. throw new JSONException("Null pointer");
  99. }
  100. if (this.mode == 'o' || this.mode == 'a') {
  101. try {
  102. if (this.comma && this.mode == 'a') {
  103. this.writer.write(',');
  104. }
  105. this.writer.write(s);
  106. } catch (IOException e) {
  107. throw new JSONException(e);
  108. }
  109. if (this.mode == 'o') {
  110. this.mode = 'k';
  111. }
  112. this.comma = true;
  113. return this;
  114. }
  115. throw new JSONException("Value out of sequence.");
  116. }
  117. /**
  118. * Begin appending a new array. All values until the balancing
  119. * <code>endArray</code> will be appended to this array. The
  120. * <code>endArray</code> method must be called to mark the array's end.
  121. * @return this
  122. * @throws JSONException If the nesting is too deep, or if the object is
  123. * started in the wrong place (for example as a key or after the end of the
  124. * outermost array or object).
  125. */
  126. public JSONWriter array() throws JSONException {
  127. if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
  128. this.push(null);
  129. this.append("[");
  130. this.comma = false;
  131. return this;
  132. }
  133. throw new JSONException("Misplaced array.");
  134. }
  135. /**
  136. * End something.
  137. * @param m Mode
  138. * @param c Closing character
  139. * @return this
  140. * @throws JSONException If unbalanced.
  141. */
  142. private JSONWriter end(char m, char c) throws JSONException {
  143. if (this.mode != m) {
  144. throw new JSONException(m == 'o' ? "Misplaced endObject." :
  145. "Misplaced endArray.");
  146. }
  147. this.pop(m);
  148. try {
  149. this.writer.write(c);
  150. } catch (IOException e) {
  151. throw new JSONException(e);
  152. }
  153. this.comma = true;
  154. return this;
  155. }
  156. /**
  157. * End an array. This method most be called to balance calls to
  158. * <code>array</code>.
  159. * @return this
  160. * @throws JSONException If incorrectly nested.
  161. */
  162. public JSONWriter endArray() throws JSONException {
  163. return this.end('a', ']');
  164. }
  165. /**
  166. * End an object. This method most be called to balance calls to
  167. * <code>object</code>.
  168. * @return this
  169. * @throws JSONException If incorrectly nested.
  170. */
  171. public JSONWriter endObject() throws JSONException {
  172. return this.end('k', '}');
  173. }
  174. /**
  175. * Append a key. The key will be associated with the next value. In an
  176. * object, every value must be preceded by a key.
  177. * @param s A key string.
  178. * @return this
  179. * @throws JSONException If the key is out of place. For example, keys
  180. * do not belong in arrays or if the key is null.
  181. */
  182. public JSONWriter key(String s) throws JSONException {
  183. if (s == null) {
  184. throw new JSONException("Null key.");
  185. }
  186. if (this.mode == 'k') {
  187. try {
  188. if (this.comma) {
  189. this.writer.write(',');
  190. }
  191. stack[top - 1].putOnce(s, Boolean.TRUE);
  192. this.writer.write(JSONObject.quote(s));
  193. this.writer.write(':');
  194. this.comma = false;
  195. this.mode = 'o';
  196. return this;
  197. } catch (IOException e) {
  198. throw new JSONException(e);
  199. }
  200. }
  201. throw new JSONException("Misplaced key.");
  202. }
  203. /**
  204. * Begin appending a new object. All keys and values until the balancing
  205. * <code>endObject</code> will be appended to this object. The
  206. * <code>endObject</code> method must be called to mark the object's end.
  207. * @return this
  208. * @throws JSONException If the nesting is too deep, or if the object is
  209. * started in the wrong place (for example as a key or after the end of the
  210. * outermost array or object).
  211. */
  212. public JSONWriter object() throws JSONException {
  213. if (this.mode == 'i') {
  214. this.mode = 'o';
  215. }
  216. if (this.mode == 'o' || this.mode == 'a') {
  217. this.append("{");
  218. this.push(new JSONObject());
  219. this.comma = false;
  220. return this;
  221. }
  222. throw new JSONException("Misplaced object.");
  223. }
  224. /**
  225. * Pop an array or object scope.
  226. * @param c The scope to close.
  227. * @throws JSONException If nesting is wrong.
  228. */
  229. private void pop(char c) throws JSONException {
  230. if (this.top <= 0) {
  231. throw new JSONException("Nesting error.");
  232. }
  233. char m = this.stack[this.top - 1] == null ? 'a' : 'k';
  234. if (m != c) {
  235. throw new JSONException("Nesting error.");
  236. }
  237. this.top -= 1;
  238. this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k';
  239. }
  240. /**
  241. * Push an array or object scope.
  242. * @param c The scope to open.
  243. * @throws JSONException If nesting is too deep.
  244. */
  245. private void push(JSONObject jo) throws JSONException {
  246. if (this.top >= maxdepth) {
  247. throw new JSONException("Nesting too deep.");
  248. }
  249. this.stack[this.top] = jo;
  250. this.mode = jo == null ? 'a' : 'k';
  251. this.top += 1;
  252. }
  253. /**
  254. * Append either the value <code>true</code> or the value
  255. * <code>false</code>.
  256. * @param b A boolean.
  257. * @return this
  258. * @throws JSONException
  259. */
  260. public JSONWriter value(boolean b) throws JSONException {
  261. return this.append(b ? "true" : "false");
  262. }
  263. /**
  264. * Append a double value.
  265. * @param d A double.
  266. * @return this
  267. * @throws JSONException If the number is not finite.
  268. */
  269. public JSONWriter value(double d) throws JSONException {
  270. return this.value(new Double(d));
  271. }
  272. /**
  273. * Append a long value.
  274. * @param l A long.
  275. * @return this
  276. * @throws JSONException
  277. */
  278. public JSONWriter value(long l) throws JSONException {
  279. return this.append(Long.toString(l));
  280. }
  281. /**
  282. * Append an object value.
  283. * @param o The object to append. It can be null, or a Boolean, Number,
  284. * String, JSONObject, or JSONArray, or an object with a toJSONString()
  285. * method.
  286. * @return this
  287. * @throws JSONException If the value is out of sequence.
  288. */
  289. public JSONWriter value(Object o) throws JSONException {
  290. return this.append(JSONObject.valueToString(o));
  291. }
  292. }