4 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:
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
16 The Software shall be used for Good, not Evil.
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27 import java.io.StringWriter;
30 * JSONStringer provides a quick and convenient way of producing JSON text.
31 * The texts produced strictly conform to JSON syntax rules. No whitespace is
32 * added, so the results are ready for transmission or storage. Each instance of
33 * JSONStringer can produce one JSON text.
35 * A JSONStringer instance provides a <code>value</code> method for appending
37 * text, and a <code>key</code>
38 * method for adding keys before values in objects. There are <code>array</code>
39 * and <code>endArray</code> methods that make and bound array values, and
40 * <code>object</code> and <code>endObject</code> methods which make and bound
41 * object values. All of these methods return the JSONWriter instance,
42 * permitting cascade style. For example, <pre>
43 * myString = new JSONStringer()
46 * .value("Hello, World!")
48 * .toString();</pre> which produces the string <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. JSONStringer 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 JSONStringer extends JSONWriter {
61 * Make a fresh JSONStringer. It can be used to build one JSON text.
63 public JSONStringer() {
64 super(new StringWriter());
68 * Return the JSON text. This method is used to obtain the product of the
69 * JSONStringer instance. It will return <code>null</code> if there was a
70 * problem in the construction of the JSON text (such as the calls to
71 * <code>array</code> were not properly balanced with calls to
72 * <code>endArray</code>).
73 * @return The JSON text.
76 public String toString() {
77 return mode == 'd' ? writer.toString() : null;