3 import java.io.IOException;
7 Copyright (c) 2006 JSON.org
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
16 The above copyright notice and this permission notice shall be included in all
17 copies or substantial portions of the Software.
19 The Software shall be used for Good, not Evil.
21 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 * JSONWriter provides a quick and convenient way of producing JSON text.
32 * The texts produced strictly conform to JSON syntax rules. No whitespace is
33 * added, so the results are ready for transmission or storage. Each instance of
34 * JSONWriter can produce one JSON text.
36 * A JSONWriter instance provides a <code>value</code> method for appending
38 * text, and a <code>key</code>
39 * method for adding keys before values in objects. There are <code>array</code>
40 * and <code>endArray</code> methods that make and bound array values, and
41 * <code>object</code> and <code>endObject</code> methods which make and bound
42 * object values. All of these methods return the JSONWriter instance,
43 * permitting a cascade style. For example, <pre>
44 * new JSONWriter(myWriter)
47 * .value("Hello, World!")
48 * .endObject();</pre> which writes <pre>
49 * {"JSON":"Hello, World!"}</pre>
51 * The first method called must be <code>array</code> or <code>object</code>.
52 * There are no methods for adding commas or colons. JSONWriter adds them for
53 * you. Objects and arrays can be nested up to 20 levels deep.
55 * This can sometimes be easier than using a JSONObject to build a string.
59 public class JSONWriter {
60 private static final int maxdepth = 200;
63 * The comma flag determines if a comma should be output before the next
66 private boolean comma;
69 * The current mode. Values:
79 * The object/array stack.
81 private final JSONObject stack[];
84 * The stack top index. A value of 0 indicates that the stack is empty.
89 * The writer that will receive the output.
91 protected Writer writer;
94 * Make a fresh JSONWriter. It can be used to build one JSON text.
96 public JSONWriter(Writer w) {
99 this.stack = new JSONObject[maxdepth];
106 * @param string A string value.
108 * @throws JSONException If the value is out of sequence.
110 private JSONWriter append(String string) throws JSONException {
111 if (string == null) {
112 throw new JSONException("Null pointer");
114 if (this.mode == 'o' || this.mode == 'a') {
116 if (this.comma && this.mode == 'a') {
117 this.writer.write(',');
119 this.writer.write(string);
120 } catch (IOException e) {
121 throw new JSONException(e);
123 if (this.mode == 'o') {
129 throw new JSONException("Value out of sequence.");
133 * Begin appending a new array. All values until the balancing
134 * <code>endArray</code> will be appended to this array. The
135 * <code>endArray</code> method must be called to mark the array's end.
137 * @throws JSONException If the nesting is too deep, or if the object is
138 * started in the wrong place (for example as a key or after the end of the
139 * outermost array or object).
141 public JSONWriter array() throws JSONException {
142 if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
148 throw new JSONException("Misplaced array.");
154 * @param c Closing character
156 * @throws JSONException If unbalanced.
158 private JSONWriter end(char mode, char c) throws JSONException {
159 if (this.mode != mode) {
160 throw new JSONException(mode == 'a'
161 ? "Misplaced endArray."
162 : "Misplaced endObject.");
166 this.writer.write(c);
167 } catch (IOException e) {
168 throw new JSONException(e);
175 * End an array. This method most be called to balance calls to
176 * <code>array</code>.
178 * @throws JSONException If incorrectly nested.
180 public JSONWriter endArray() throws JSONException {
181 return this.end('a', ']');
185 * End an object. This method most be called to balance calls to
186 * <code>object</code>.
188 * @throws JSONException If incorrectly nested.
190 public JSONWriter endObject() throws JSONException {
191 return this.end('k', '}');
195 * Append a key. The key will be associated with the next value. In an
196 * object, every value must be preceded by a key.
197 * @param string A key string.
199 * @throws JSONException If the key is out of place. For example, keys
200 * do not belong in arrays or if the key is null.
202 public JSONWriter key(String string) throws JSONException {
203 if (string == null) {
204 throw new JSONException("Null key.");
206 if (this.mode == 'k') {
208 this.stack[this.top - 1].putOnce(string, Boolean.TRUE);
210 this.writer.write(',');
212 this.writer.write(JSONObject.quote(string));
213 this.writer.write(':');
217 } catch (IOException e) {
218 throw new JSONException(e);
221 throw new JSONException("Misplaced key.");
226 * Begin appending a new object. All keys and values until the balancing
227 * <code>endObject</code> will be appended to this object. The
228 * <code>endObject</code> method must be called to mark the object's end.
230 * @throws JSONException If the nesting is too deep, or if the object is
231 * started in the wrong place (for example as a key or after the end of the
232 * outermost array or object).
234 public JSONWriter object() throws JSONException {
235 if (this.mode == 'i') {
238 if (this.mode == 'o' || this.mode == 'a') {
240 this.push(new JSONObject());
244 throw new JSONException("Misplaced object.");
250 * Pop an array or object scope.
251 * @param c The scope to close.
252 * @throws JSONException If nesting is wrong.
254 private void pop(char c) throws JSONException {
256 throw new JSONException("Nesting error.");
258 char m = this.stack[this.top - 1] == null ? 'a' : 'k';
260 throw new JSONException("Nesting error.");
263 this.mode = this.top == 0
265 : this.stack[this.top - 1] == null
271 * Push an array or object scope.
272 * @param jo The scope to open.
273 * @throws JSONException If nesting is too deep.
275 private void push(JSONObject jo) throws JSONException {
276 if (this.top >= maxdepth) {
277 throw new JSONException("Nesting too deep.");
279 this.stack[this.top] = jo;
280 this.mode = jo == null ? 'a' : 'k';
286 * Append either the value <code>true</code> or the value
287 * <code>false</code>.
288 * @param b A boolean.
290 * @throws JSONException
292 public JSONWriter value(boolean b) throws JSONException {
293 return this.append(b ? "true" : "false");
297 * Append a double value.
300 * @throws JSONException If the number is not finite.
302 public JSONWriter value(double d) throws JSONException {
303 return this.value(new Double(d));
307 * Append a long value.
310 * @throws JSONException
312 public JSONWriter value(long l) throws JSONException {
313 return this.append(Long.toString(l));
318 * Append an object value.
319 * @param object The object to append. It can be null, or a Boolean, Number,
320 * String, JSONObject, or JSONArray, or an object that implements JSONString.
322 * @throws JSONException If the value is out of sequence.
324 public JSONWriter value(Object object) throws JSONException {
325 return this.append(JSONObject.valueToString(object));