forked from mongodb/mongo-java-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSON.java
More file actions
558 lines (495 loc) · 14.3 KB
/
JSON.java
File metadata and controls
558 lines (495 loc) · 14.3 KB
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
// JSON.java
/**
* Copyright (C) 2008 10gen Inc.
*
* Licensed 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.
*/
package com.mongodb.util;
import org.bson.BSONCallback;
import com.mongodb.DBObject;
/**
* Helper methods for JSON serialization and de-serialization
*/
public class JSON {
/**
* Serializes an object into its JSON form.
* <p>
* This method delegates serialization to <code>JSONSerializers.getLegacy</code>
*
* @param o object to serialize
* @return String containing JSON form of the object
* @see com.mongodb.util.JSONSerializers#getLegacy()
*/
public static String serialize( Object o ){
StringBuilder buf = new StringBuilder();
serialize( o , buf );
return buf.toString();
}
/**
* Serializes an object into its JSON form.
* <p>
* This method delegates serialization to <code>JSONSerializers.getLegacy</code>
*
* @param o object to serialize
* @param buf StringBuilder containing the JSON representation under construction
* @return String containing JSON form of the object
* @see com.mongodb.util.JSONSerializers#getLegacy()
*/
public static void serialize( Object o, StringBuilder buf) {
JSONSerializers.getLegacy().serialize(o, buf);
}
/**
* Parses a JSON string representing a JSON value
*
* @param s the string to parse
* @return the object
*/
public static Object parse( String s ){
return parse(s, null);
}
/**
* Parses a JSON string representing a JSON value
*
* @param s the string to parse
* @return the object
*/
public static Object parse( String s, BSONCallback c ){
if (s == null || (s=s.trim()).equals("")) {
return (DBObject)null;
}
JSONParser p = new JSONParser(s, c);
return p.parse();
}
static void string( StringBuilder a , String s ){
a.append("\"");
for(int i = 0; i < s.length(); ++i){
char c = s.charAt(i);
if (c == '\\')
a.append("\\\\");
else if(c == '"')
a.append("\\\"");
else if(c == '\n')
a.append("\\n");
else if(c == '\r')
a.append("\\r");
else if(c == '\t')
a.append("\\t");
else if(c == '\b')
a.append("\\b");
else if ( c < 32 )
continue;
else
a.append(c);
}
a.append("\"");
}
}
/**
* Parser for JSON objects.
*
* Supports all types described at www.json.org, except for
* numbers with "e" or "E" in them.
*/
class JSONParser {
String s;
int pos = 0;
BSONCallback _callback;
/**
* Create a new parser.
*/
public JSONParser(String s) {
this(s, null);
}
/**
* Create a new parser.
*/
public JSONParser(String s, BSONCallback callback) {
this.s = s;
_callback = (callback == null) ? new JSONCallback() : callback;
}
/**
* Parse an unknown type.
*
* @return Object the next item
* @throws JSONParseException if invalid JSON is found
*/
public Object parse() {
return parse(null);
}
/**
* Parse an unknown type.
*
* @return Object the next item
* @throws JSONParseException if invalid JSON is found
*/
protected Object parse(String name) {
Object value = null;
char current = get();
switch(current) {
// null
case 'n':
read('n'); read('u'); read('l'); read('l');
value = null;
break;
// NaN
case 'N':
read('N'); read('a'); read('N');
value = Double.NaN;
break;
// true
case 't':
read('t'); read('r'); read('u'); read('e');
value = true;
break;
// false
case 'f':
read('f'); read('a'); read('l'); read('s'); read('e');
value = false;
break;
// string
case '\'':
case '\"':
value = parseString(true);
break;
// number
case '0': case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9': case '+': case '-':
value = parseNumber();
break;
// array
case '[':
value = parseArray(name);
break;
// object
case '{':
value = parseObject(name);
break;
default:
throw new JSONParseException(s, pos);
}
return value;
}
/**
* Parses an object for the form <i>{}</i> and <i>{ members }</i>.
*
* @return DBObject the next object
* @throws JSONParseException if invalid JSON is found
*/
public Object parseObject() {
return parseObject(null);
}
/**
* Parses an object for the form <i>{}</i> and <i>{ members }</i>.
*
* @return DBObject the next object
* @throws JSONParseException if invalid JSON is found
*/
protected Object parseObject(String name){
if (name != null) {
_callback.objectStart(name);
} else {
_callback.objectStart();
}
read('{');
char current = get();
while(get() != '}') {
String key = parseString(false);
read(':');
Object value = parse(key);
doCallback(key, value);
if((current = get()) == ',') {
read(',');
}
else {
break;
}
}
read('}');
return _callback.objectDone();
}
protected void doCallback(String name, Object value) {
if (value == null) {
_callback.gotNull(name);
} else if (value instanceof String) {
_callback.gotString(name, (String)value);
} else if (value instanceof Boolean) {
_callback.gotBoolean(name, (Boolean)value);
} else if (value instanceof Integer) {
_callback.gotInt(name, (Integer)value);
} else if (value instanceof Long) {
_callback.gotLong(name, (Long)value);
} else if (value instanceof Double) {
_callback.gotDouble(name, (Double)value);
}
}
/**
* Read the current character, making sure that it is the expected character.
* Advances the pointer to the next character.
*
* @param ch the character expected
*
* @throws JSONParseException if the current character does not match the given character
*/
public void read(char ch) {
if(!check(ch)) {
throw new JSONParseException(s, pos);
}
pos++;
}
public char read(){
if ( pos >= s.length() )
throw new IllegalStateException( "string done" );
return s.charAt( pos++ );
}
/**
* Read the current character, making sure that it is a hexidecimal character.
*
* @throws JSONParseException if the current character is not a hexidecimal character
*/
public void readHex() {
if (pos < s.length() &&
((s.charAt(pos) >= '0' && s.charAt(pos) <= '9') ||
(s.charAt(pos) >= 'A' && s.charAt(pos) <= 'F') ||
(s.charAt(pos) >= 'a' && s.charAt(pos) <= 'f'))) {
pos++;
}
else {
throw new JSONParseException(s, pos);
}
}
/**
* Checks the current character, making sure that it is the expected character.
*
* @param ch the character expected
*
* @throws JSONParseException if the current character does not match the given character
*/
public boolean check(char ch) {
return get() == ch;
}
/**
* Advances the position in the string past any whitespace.
*/
public void skipWS() {
while(pos < s.length() && Character.isWhitespace(s.charAt(pos))) {
pos++;
}
}
/**
* Returns the current character.
* Returns -1 if there are no more characters.
*
* @return the next character
*/
public char get() {
skipWS();
if(pos < s.length())
return s.charAt(pos);
return (char)-1;
}
/**
* Parses a string.
*
* @return the next string.
* @throws JSONParseException if invalid JSON is found
*/
public String parseString(boolean needQuote) {
char quot = 0;
if(check('\''))
quot = '\'';
else if(check('\"'))
quot = '\"';
else if (needQuote)
throw new JSONParseException(s, pos);
char current;
if (quot > 0)
read(quot);
StringBuilder buf = new StringBuilder();
int start = pos;
while(pos < s.length()) {
current = s.charAt(pos);
if (quot > 0) {
if (current == quot)
break;
} else {
if (current == ':' || current == ' ')
break;
}
if(current == '\\') {
pos++;
char x = get();
char special = 0;
switch ( x ){
case 'u':
{ // decode unicode
buf.append(s.substring(start, pos-1));
pos++;
int tempPos = pos;
readHex();
readHex();
readHex();
readHex();
int codePoint = Integer.parseInt(s.substring(tempPos, tempPos+4), 16);
buf.append((char)codePoint);
start = pos;
continue;
}
case 'n': special = '\n'; break;
case 'r': special = '\r'; break;
case 't': special = '\t'; break;
case 'b': special = '\b'; break;
case '"': special = '\"'; break;
case '\\': special = '\\'; break;
}
buf.append(s.substring(start, pos-1));
if ( special != 0 ){
pos++;
buf.append( special );
}
start = pos;
continue;
}
pos++;
}
buf.append(s.substring(start, pos));
if (quot > 0)
read(quot);
return buf.toString();
}
/**
* Parses a number.
*
* @return the next number (int or double).
* @throws JSONParseException if invalid JSON is found
*/
public Number parseNumber() {
char current = get();
int start = this.pos;
boolean isDouble = false;
if(check('-') || check('+')) {
pos++;
}
outer:
while(pos < s.length()) {
switch(s.charAt(pos)) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
pos++;
break;
case '.':
isDouble = true;
parseFraction();
break;
case 'e': case 'E':
isDouble = true;
parseExponent();
break;
default:
break outer;
}
}
try{
if (isDouble)
return Double.valueOf(s.substring(start, pos));
Long val = Long.valueOf(s.substring(start, pos));
if (val <= Integer.MAX_VALUE && val >= Integer.MIN_VALUE)
return val.intValue();
return val;
}catch(NumberFormatException e){
throw new JSONParseException(s, start, e);
}
}
/**
* Advances the pointed through <i>.digits</i>.
*/
public void parseFraction() {
// get past .
pos++;
outer:
while(pos < s.length()) {
switch(s.charAt(pos)) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
pos++;
break;
case 'e': case 'E':
parseExponent();
break;
default:
break outer;
}
}
}
/**
* Advances the pointer through the exponent.
*/
public void parseExponent() {
// get past E
pos++;
if(check('-') || check('+')) {
pos++;
}
outer:
while(pos < s.length()) {
switch(s.charAt(pos)) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
pos++;
break;
default:
break outer;
}
}
}
/**
* Parses the next array.
*
* @return the array
* @throws JSONParseException if invalid JSON is found
*/
public Object parseArray() {
return parseArray(null);
}
/**
* Parses the next array.
*
* @return the array
* @throws JSONParseException if invalid JSON is found
*/
protected Object parseArray(String name) {
if (name != null) {
_callback.arrayStart(name);
} else {
_callback.arrayStart();
}
read('[');
int i = 0;
char current = get();
while( current != ']' ) {
String elemName = String.valueOf(i++);
Object elem = parse(elemName);
doCallback(elemName, elem);
if((current = get()) == ',') {
read(',');
}
else if(current == ']') {
break;
}
else {
throw new JSONParseException(s, pos);
}
}
read(']');
return _callback.arrayDone();
}
}