-
Notifications
You must be signed in to change notification settings - Fork 42
/
JsonOutput.java
342 lines (296 loc) · 10.6 KB
/
JsonOutput.java
1
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package grails.plugin.json.builder;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import groovy.json.JsonException;
import groovy.json.JsonLexer;
import groovy.json.JsonToken;
import groovy.lang.Closure;
import groovy.lang.Writable;
import groovy.util.Expando;
import org.apache.groovy.json.internal.CharBuf;
import org.apache.groovy.json.internal.Chr;
import org.grails.buffer.FastStringWriter;
import java.io.*;
import java.net.URL;
import java.util.*;
/**
* Temporary fork of {@link groovy.json.JsonOutput} until Groovy 2.5.0 is out.
*
* Class responsible for the actual String serialization of the possible values of a JSON structure.
* This class can also be used as a category, so as to add <code>toJson()</code> methods to various types.
*
* @author Guillaume Laforge
* @author Roshan Dawrani
* @author Andrey Bloschetsov
* @author Rick Hightower
* @author Graeme Rocher
*
* @since 1.8.0
*/
public class JsonOutput {
public static final char OPEN_BRACKET = '[';
public static final char CLOSE_BRACKET = ']';
public static final char OPEN_BRACE = '{';
public static final char CLOSE_BRACE = '}';
public static final char COLON = ':';
public static final char COMMA = ',';
public static final char SPACE = ' ';
public static final char NEW_LINE = '\n';
public static final char QUOTE = '"';
public static final String NULL_VALUE = "null";
public static final String JSON_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static final String DEFAULT_TIMEZONE = "GMT";
static final char[] EMPTY_STRING_CHARS = Chr.array(QUOTE, QUOTE);
static final char[] EMPTY_MAP_CHARS = {OPEN_BRACE, CLOSE_BRACE};
static final char[] EMPTY_LIST_CHARS = {OPEN_BRACKET, CLOSE_BRACKET};
static final JsonGenerator DEFAULT_GENERATOR;
static {
JsonGenerator.Options options = new JsonGenerator.Options()
.disableUnicodeEscaping()
.dateFormat(JSON_DATE_FORMAT)
.timezone(DEFAULT_TIMEZONE);
DEFAULT_GENERATOR = new DefaultJsonGenerator(options);
}
/**
* @param bool a {@link Boolean}
* @return "true" or "false" for a boolean value
*/
public static String toJson(Boolean bool) {
return DEFAULT_GENERATOR.toJson(bool);
}
/**
* @param n a {@link Number} to write as JSON string
* @return a string representation for a number
* @throws groovy.json.JsonException
* If the number is infinite or not a number
*/
public static String toJson(Number n) {
return DEFAULT_GENERATOR.toJson(n);
}
/**
* @param c a {@link Character}
* @return a JSON string representation of the character
*/
public static String toJson(Character c) {
return DEFAULT_GENERATOR.toJson(c);
}
/**
* @param s a {@link String} to be represented in JSON
* @return a properly encoded string with escape sequences
*/
public static String toJson(String s) {
return DEFAULT_GENERATOR.toJson(s);
}
/**
* Format a date that is parseable from JavaScript, according to ISO-8601.
*
* @param date the date to format to a JSON string
* @return a formatted date in the form of a string
*/
public static String toJson(Date date) {
return DEFAULT_GENERATOR.toJson(date);
}
/**
* Format a calendar instance that is parseable from JavaScript, according to ISO-8601.
*
* @param cal the calendar to format to a JSON string
* @return a formatted date in the form of a string
*/
public static String toJson(Calendar cal) {
return DEFAULT_GENERATOR.toJson(cal);
}
/**
* @param uuid a {@link UUID}
* @return the string representation of an uuid
*/
public static String toJson(UUID uuid) {
return DEFAULT_GENERATOR.toJson(uuid);
}
/**
* @param url a {@link URL}
* @return the string representation of the URL
*/
public static String toJson(URL url) {
return DEFAULT_GENERATOR.toJson(url);
}
/**
* @param closure a {@link Closure} to format to JSON string
* @return an object representation of a closure
*/
public static String toJson(Closure closure) {
return DEFAULT_GENERATOR.toJson(closure);
}
/**
* @param expando a {@link Expando} object to format to JSON string
* @return an object representation of an Expando
*/
public static String toJson(Expando expando) {
return DEFAULT_GENERATOR.toJson(expando);
}
/**
* @param object an {@link Object} to format to JSON string
* @return "null" for a null value, or a JSON array representation for a collection, array, iterator or enumeration,
* or representation for other object.
*/
public static String toJson(Object object) {
return DEFAULT_GENERATOR.toJson(object);
}
/**
* @param m a {@link Map} to format to JSON string
* @return a JSON object representation for a map
*/
public static String toJson(Map m) {
return DEFAULT_GENERATOR.toJson(m);
}
/**
* Pretty print a JSON payload.
*
* @param jsonPayload a JSON payload
* @return a pretty representation of JSON payload.
*/
public static String prettyPrint(String jsonPayload) {
int indentSize = 0;
// Just a guess that the pretty view will take a 20 percent more than original.
final CharBuf output = CharBuf.create((int) (jsonPayload.length() * 1.2));
JsonLexer lexer = new JsonLexer(new StringReader(jsonPayload));
// Will store already created indents.
Map<Integer, char[]> indentCache = new HashMap<Integer, char[]>();
while (lexer.hasNext()) {
JsonToken token = lexer.next();
switch (token.getType()) {
case OPEN_CURLY:
indentSize += 4;
output.addChars(Chr.array(OPEN_BRACE, NEW_LINE)).addChars(getIndent(indentSize, indentCache));
break;
case CLOSE_CURLY:
indentSize -= 4;
output.addChar(NEW_LINE);
if (indentSize > 0) {
output.addChars(getIndent(indentSize, indentCache));
}
output.addChar(CLOSE_BRACE);
break;
case OPEN_BRACKET:
indentSize += 4;
output.addChars(Chr.array(OPEN_BRACKET, NEW_LINE)).addChars(getIndent(indentSize, indentCache));
break;
case CLOSE_BRACKET:
indentSize -= 4;
output.addChar(NEW_LINE);
if (indentSize > 0) {
output.addChars(getIndent(indentSize, indentCache));
}
output.addChar(CLOSE_BRACKET);
break;
case COMMA:
output.addChars(Chr.array(COMMA, NEW_LINE)).addChars(getIndent(indentSize, indentCache));
break;
case COLON:
output.addChars(Chr.array(COLON, SPACE));
break;
case STRING:
String textStr = token.getText();
String textWithoutQuotes = textStr.substring(1, textStr.length() - 1);
if (textWithoutQuotes.length() > 0) {
output.addJsonEscapedString(textWithoutQuotes);
} else {
output.addQuoted(Chr.array());
}
break;
default:
output.addString(token.getText());
}
}
return output.toString();
}
/**
* Creates new indent if it not exists in the indent cache.
*
* @return indent with the specified size.
*/
private static char[] getIndent(int indentSize, Map<Integer, char[]> indentCache) {
char[] indent = indentCache.get(indentSize);
if (indent == null) {
indent = new char[indentSize];
Arrays.fill(indent, SPACE);
indentCache.put(indentSize, indent);
}
return indent;
}
/**
* Obtains JSON unescaped text for the given text
*
* @param text The text
* @return The unescaped text
*/
public static JsonUnescaped unescaped(CharSequence text) {
return new JsonUnescaped(text);
}
/**
* Represents unescaped JSON
*/
public static class JsonUnescaped {
private CharSequence text;
public JsonUnescaped(CharSequence text) {
this.text = text;
}
public CharSequence getText() {
return text;
}
@Override
public String toString() {
return text.toString();
}
}
/**
* Represents unescaped JSON
*/
public static abstract class JsonWritable implements Writable, CharSequence {
protected boolean inline = false;
protected boolean first = true;
public void setInline(boolean inline) {
this.inline = inline;
}
public void setFirst(boolean first) {
this.first = first;
}
@Override
public String toString() {
FastStringWriter out = new FastStringWriter();
try {
writeTo(out);
} catch (IOException e) {
throw new JsonException("Error writing JSON writable: " + e.getMessage(), e);
}
return out.toString();
}
@Override
public int length() {
return toString().length();
}
@Override
public char charAt(int index) {
return toString().charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return toString().subSequence(start, end);
}
}
}