1 package atg.taglib.json.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 import java.io.StringWriter;
28
29 /**
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.
34 * <p>
35 * A JSONStringer instance provides a <code>value</code> method for appending
36 * values to the
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()
44 * .object()
45 * .key("JSON")
46 * .value("Hello, World!")
47 * .endObject()
48 * .toString();</pre> which produces the string <pre>
49 * {"JSON":"Hello, World!"}</pre>
50 * <p>
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.
54 * <p>
55 * This can sometimes be easier than using a JSONObject to build a string.
56 * @author JSON.org
57 * @version 2
58 */
59 public class JSONStringer extends JSONWriter {
60 /**
61 * Make a fresh JSONStringer. It can be used to build one JSON text.
62 */
63 public JSONStringer() {
64 super(new StringWriter());
65 }
66
67 /**
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.
74 */
75 public String toString() {
76 return this.mode == 'd' ? this.writer.toString() : null;
77 }
78 }