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 2015-12-09
058 */
059public class JSONWriter {
060    private static final int maxdepth = 200;
061
062    /**
063     * The comma flag determines if a comma should be output before the next
064     * value.
065     */
066    private boolean comma;
067
068    /**
069     * The current mode. Values:
070     * 'a' (array),
071     * 'd' (done),
072     * 'i' (initial),
073     * 'k' (key),
074     * 'o' (object).
075     */
076    protected char mode;
077
078    /**
079     * The object/array stack.
080     */
081    private final JSONObject stack[];
082
083    /**
084     * The stack top index. A value of 0 indicates that the stack is empty.
085     */
086    private int top;
087
088    /**
089     * The writer that will receive the output.
090     */
091    protected Writer writer;
092
093    /**
094     * Make a fresh JSONWriter. It can be used to build one JSON text.
095     */
096    public JSONWriter(Writer w) {
097        this.comma = false;
098        this.mode = 'i';
099        this.stack = new JSONObject[maxdepth];
100        this.top = 0;
101        this.writer = w;
102    }
103
104    /**
105     * Append a value.
106     * @param string A string value.
107     * @return this
108     * @throws JSONException If the value is out of sequence.
109     */
110    private JSONWriter append(String string) throws JSONException {
111        if (string == null) {
112            throw new JSONException("Null pointer");
113        }
114        if (this.mode == 'o' || this.mode == 'a') {
115            try {
116                if (this.comma && this.mode == 'a') {
117                    this.writer.write(',');
118                }
119                this.writer.write(string);
120            } catch (IOException e) {
121                throw new JSONException(e);
122            }
123            if (this.mode == 'o') {
124                this.mode = 'k';
125            }
126            this.comma = true;
127            return this;
128        }
129        throw new JSONException("Value out of sequence.");
130    }
131
132    /**
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.
136     * @return this
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).
140     */
141    public JSONWriter array() throws JSONException {
142        if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
143            this.push(null);
144            this.append("[");
145            this.comma = false;
146            return this;
147        }
148        throw new JSONException("Misplaced array.");
149    }
150
151    /**
152     * End something.
153     * @param mode Mode
154     * @param c Closing character
155     * @return this
156     * @throws JSONException If unbalanced.
157     */
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.");
163        }
164        this.pop(mode);
165        try {
166            this.writer.write(c);
167        } catch (IOException e) {
168            throw new JSONException(e);
169        }
170        this.comma = true;
171        return this;
172    }
173
174    /**
175     * End an array. This method most be called to balance calls to
176     * <code>array</code>.
177     * @return this
178     * @throws JSONException If incorrectly nested.
179     */
180    public JSONWriter endArray() throws JSONException {
181        return this.end('a', ']');
182    }
183
184    /**
185     * End an object. This method most be called to balance calls to
186     * <code>object</code>.
187     * @return this
188     * @throws JSONException If incorrectly nested.
189     */
190    public JSONWriter endObject() throws JSONException {
191        return this.end('k', '}');
192    }
193
194    /**
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.
198     * @return this
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.
201     */
202    public JSONWriter key(String string) throws JSONException {
203        if (string == null) {
204            throw new JSONException("Null key.");
205        }
206        if (this.mode == 'k') {
207            try {
208                this.stack[this.top - 1].putOnce(string, Boolean.TRUE);
209                if (this.comma) {
210                    this.writer.write(',');
211                }
212                this.writer.write(JSONObject.quote(string));
213                this.writer.write(':');
214                this.comma = false;
215                this.mode = 'o';
216                return this;
217            } catch (IOException e) {
218                throw new JSONException(e);
219            }
220        }
221        throw new JSONException("Misplaced key.");
222    }
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     * @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).
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    /**
250     * Pop an array or object scope.
251     * @param c The scope to close.
252     * @throws JSONException If nesting is wrong.
253     */
254    private void pop(char c) throws JSONException {
255        if (this.top <= 0) {
256            throw new JSONException("Nesting error.");
257        }
258        char m = this.stack[this.top - 1] == null ? 'a' : 'k';
259        if (m != c) {
260            throw new JSONException("Nesting error.");
261        }
262        this.top -= 1;
263        this.mode = this.top == 0
264            ? 'd'
265            : this.stack[this.top - 1] == null
266            ? 'a'
267            : 'k';
268    }
269
270    /**
271     * Push an array or object scope.
272     * @param jo The scope to open.
273     * @throws JSONException If nesting is too deep.
274     */
275    private void push(JSONObject jo) throws JSONException {
276        if (this.top >= maxdepth) {
277            throw new JSONException("Nesting too deep.");
278        }
279        this.stack[this.top] = jo;
280        this.mode = jo == null ? 'a' : 'k';
281        this.top += 1;
282    }
283
284
285    /**
286     * Append either the value <code>true</code> or the value
287     * <code>false</code>.
288     * @param b A boolean.
289     * @return this
290     * @throws JSONException
291     */
292    public JSONWriter value(boolean b) throws JSONException {
293        return this.append(b ? "true" : "false");
294    }
295
296    /**
297     * Append a double value.
298     * @param d A double.
299     * @return this
300     * @throws JSONException If the number is not finite.
301     */
302    public JSONWriter value(double d) throws JSONException {
303        return this.value(new Double(d));
304    }
305
306    /**
307     * Append a long value.
308     * @param l A long.
309     * @return this
310     * @throws JSONException
311     */
312    public JSONWriter value(long l) throws JSONException {
313        return this.append(Long.toString(l));
314    }
315
316
317    /**
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.
321     * @return this
322     * @throws JSONException If the value is out of sequence.
323     */
324    public JSONWriter value(Object object) throws JSONException {
325        return this.append(JSONObject.valueToString(object));
326    }
327}