001package org.json;
002
003import java.io.IOException;
004import java.io.Writer;
005
006/*
007Copyright (c) 2006 JSON.org
008
009Permission is hereby granted, free of charge, to any person obtaining a copy
010of this software and associated documentation files (the "Software"), to deal
011in the Software without restriction, including without limitation the rights
012to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
013copies of the Software, and to permit persons to whom the Software is
014furnished to do so, subject to the following conditions:
015
016The above copyright notice and this permission notice shall be included in all
017copies or substantial portions of the Software.
018
019The Software shall be used for Good, not Evil.
020
021THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
022IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
023FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
024AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
025LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
026OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
027SOFTWARE.
028 */
029
030/**
031 * JSONWriter provides a quick and convenient way of producing JSON text.
032 * The texts produced strictly conform to JSON syntax rules. No whitespace is
033 * added, so the results are ready for transmission or storage. Each instance of
034 * JSONWriter can produce one JSON text.
035 * <p>
036 * A JSONWriter instance provides a <code>value</code> method for appending
037 * values to the
038 * text, and a <code>key</code>
039 * method for adding keys before values in objects. There are <code>array</code>
040 * and <code>endArray</code> methods that make and bound array values, and
041 * <code>object</code> and <code>endObject</code> methods which make and bound
042 * object values. All of these methods return the JSONWriter instance,
043 * permitting a cascade style. For example, <pre>
044 * new JSONWriter(myWriter)
045 *     .object()
046 *         .key("JSON")
047 *         .value("Hello, World!")
048 *     .endObject();</pre> which writes <pre>
049 * {"JSON":"Hello, World!"}</pre>
050 * <p>
051 * The first method called must be <code>array</code> or <code>object</code>.
052 * There are no methods for adding commas or colons. JSONWriter adds them for
053 * you. Objects and arrays can be nested up to 20 levels deep.
054 * <p>
055 * This can sometimes be easier than using a JSONObject to build a string.
056 * @author JSON.org
057@version $Id$
058@since Ptolemy II 10.0
059 * @version 2010-03-11
060 */
061public class JSONWriter {
062    private static final int maxdepth = 20;
063
064    /**
065     * The comma flag determines if a comma should be output before the next
066     * value.
067     */
068    private boolean comma;
069
070    /**
071     * The current mode. Values:
072     * 'a' (array),
073     * 'd' (done),
074     * 'i' (initial),
075     * 'k' (key),
076     * 'o' (object).
077     */
078    protected char mode;
079
080    /**
081     * The object/array stack.
082     */
083    private JSONObject stack[];
084
085    /**
086     * The stack top index. A value of 0 indicates that the stack is empty.
087     */
088    private int top;
089
090    /**
091     * The writer that will receive the output.
092     */
093    protected Writer writer;
094
095    /**
096     * Make a fresh JSONWriter. It can be used to build one JSON text.
097     */
098    public JSONWriter(Writer w) {
099        this.comma = false;
100        this.mode = 'i';
101        this.stack = new JSONObject[maxdepth];
102        this.top = 0;
103        this.writer = w;
104    }
105
106    /**
107     * Append a value.
108     * @param s A string value.
109     * @return this
110     * @exception JSONException If the value is out of sequence.
111     */
112    private JSONWriter append(String s) throws JSONException {
113        if (s == null) {
114            throw new JSONException("Null pointer");
115        }
116        if (this.mode == 'o' || this.mode == 'a') {
117            try {
118                if (this.comma && this.mode == 'a') {
119                    this.writer.write(',');
120                }
121                this.writer.write(s);
122            } catch (IOException e) {
123                throw new JSONException(e);
124            }
125            if (this.mode == 'o') {
126                this.mode = 'k';
127            }
128            this.comma = true;
129            return this;
130        }
131        throw new JSONException("Value out of sequence.");
132    }
133
134    /**
135     * Begin appending a new array. All values until the balancing
136     * <code>endArray</code> will be appended to this array. The
137     * <code>endArray</code> method must be called to mark the array's end.
138     * @return this
139     * @exception JSONException If the nesting is too deep, or if the object is
140     * started in the wrong place (for example as a key or after the end of the
141     * outermost array or object).
142     */
143    public JSONWriter array() throws JSONException {
144        if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
145            this.push(null);
146            this.append("[");
147            this.comma = false;
148            return this;
149        }
150        throw new JSONException("Misplaced array.");
151    }
152
153    /**
154     * End something.
155     * @param m Mode
156     * @param c Closing character
157     * @return this
158     * @exception JSONException If unbalanced.
159     */
160    private JSONWriter end(char m, char c) throws JSONException {
161        if (this.mode != m) {
162            throw new JSONException(
163                    m == 'a' ? "Misplaced endArray." : "Misplaced endObject.");
164        }
165        this.pop(m);
166        try {
167            this.writer.write(c);
168        } catch (IOException e) {
169            throw new JSONException(e);
170        }
171        this.comma = true;
172        return this;
173    }
174
175    /**
176     * End an array. This method most be called to balance calls to
177     * <code>array</code>.
178     * @return this
179     * @exception JSONException If incorrectly nested.
180     */
181    public JSONWriter endArray() throws JSONException {
182        return this.end('a', ']');
183    }
184
185    /**
186     * End an object. This method most be called to balance calls to
187     * <code>object</code>.
188     * @return this
189     * @exception JSONException If incorrectly nested.
190     */
191    public JSONWriter endObject() throws JSONException {
192        return this.end('k', '}');
193    }
194
195    /**
196     * Append a key. The key will be associated with the next value. In an
197     * object, every value must be preceded by a key.
198     * @param s A key string.
199     * @return this
200     * @exception JSONException If the key is out of place. For example, keys
201     *  do not belong in arrays or if the key is null.
202     */
203    public JSONWriter key(String s) throws JSONException {
204        if (s == null) {
205            throw new JSONException("Null key.");
206        }
207        if (this.mode == 'k') {
208            try {
209                stack[top - 1].putOnce(s, Boolean.TRUE);
210                if (this.comma) {
211                    this.writer.write(',');
212                }
213                this.writer.write(JSONObject.quote(s));
214                this.writer.write(':');
215                this.comma = false;
216                this.mode = 'o';
217                return this;
218            } catch (IOException e) {
219                throw new JSONException(e);
220            }
221        }
222        throw new JSONException("Misplaced key.");
223    }
224
225    /**
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.
229     * @return this
230     * @exception 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).
233     */
234    public JSONWriter object() throws JSONException {
235        if (this.mode == 'i') {
236            this.mode = 'o';
237        }
238        if (this.mode == 'o' || this.mode == 'a') {
239            this.append("{");
240            this.push(new JSONObject());
241            this.comma = false;
242            return this;
243        }
244        throw new JSONException("Misplaced object.");
245
246    }
247
248    /**
249     * Pop an array or object scope.
250     * @param c The scope to close.
251     * @exception JSONException If nesting is wrong.
252     */
253    private void pop(char c) throws JSONException {
254        if (this.top <= 0) {
255            throw new JSONException("Nesting error.");
256        }
257        char m = this.stack[this.top - 1] == null ? 'a' : 'k';
258        if (m != c) {
259            throw new JSONException("Nesting error.");
260        }
261        this.top -= 1;
262        this.mode = this.top == 0 ? 'd'
263                : this.stack[this.top - 1] == null ? 'a' : 'k';
264    }
265
266    /**
267     * Push an array or object scope.
268     * @param jo The array or object scope.
269     * @exception JSONException If nesting is too deep.
270     */
271    private void push(JSONObject jo) throws JSONException {
272        if (this.top >= maxdepth) {
273            throw new JSONException("Nesting too deep.");
274        }
275        this.stack[this.top] = jo;
276        this.mode = jo == null ? 'a' : 'k';
277        this.top += 1;
278    }
279
280    /**
281     * Append either the value <code>true</code> or the value
282     * <code>false</code>.
283     * @param b A boolean.
284     * @return this
285     * @exception JSONException
286     */
287    public JSONWriter value(boolean b) throws JSONException {
288        return this.append(b ? "true" : "false");
289    }
290
291    /**
292     * Append a double value.
293     * @param d A double.
294     * @return this
295     * @exception JSONException If the number is not finite.
296     */
297    public JSONWriter value(double d) throws JSONException {
298        return this.value(new Double(d));
299    }
300
301    /**
302     * Append a long value.
303     * @param l A long.
304     * @return this
305     * @exception JSONException
306     */
307    public JSONWriter value(long l) throws JSONException {
308        return this.append(Long.toString(l));
309    }
310
311    /**
312     * Append an object value.
313     * @param o The object to append. It can be null, or a Boolean, Number,
314     *   String, JSONObject, or JSONArray, or an object with a toJSONString()
315     *   method.
316     * @return this
317     * @exception JSONException If the value is out of sequence.
318     */
319    public JSONWriter value(Object o) throws JSONException {
320        return this.append(JSONObject.valueToString(o));
321    }
322}