-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONObject.java
More file actions
559 lines (518 loc) · 19.1 KB
/
Copy pathJSONObject.java
File metadata and controls
559 lines (518 loc) · 19.1 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
559
/*
* This class includes a majority of the JSON parser
*/
// Import ArrayList and HashMap for data storage
import java.util.ArrayList;
import java.util.HashMap;
// Import Constructor for calling a constructor to create an object
import java.lang.reflect.Constructor;
public class JSONObject {
// Stores data for object types
HashMap<String, Object> objData;
// Stores data for array types
ArrayList<Object> arrData;
// Type of this JSONObject
Types type;
/*
* Constructor
*/
public JSONObject(String data, Types type) {
this.type = type;
// Parse according to type
if(type == Types.OBJECT) {
objData = parseObj(data);
} else if (type == Types.ARRAY) {
arrData = parseArray(data);
}
}
/**
* Parses an array from a given data between the two square brackets
*
* @param data the data between the square brackets
* @return an ArrayList of all of the data in the array
**/
private ArrayList<Object> parseArray(String data) {
// Declare and initialize ArrayList
ArrayList<Object> result = new ArrayList<Object>();
// Arrays for storing characters to look for
char[] openChars = {'{', '['};
char[] closeChars = {'}', ']'};
char[] openAndClose = {'"'};
// Arrays for storing data for parsing based on above characters
int[] depths = {0, 0};
int[] values = {0};
// Content of a certain data type
String currentContent = "";
// Initial type is NONE, the equivalent of null in this parser
Types currentType = Types.NONE;
// Declare i outside of for loop so we can use it later on
int i = 0;
// Loop through data
for(; i < data.length(); i++) {
// Get current character
char thisChar = data.charAt(i);
if(thisChar == '\\') {
// Escape codes
// - Currently only supports \n, \t, \\, and escaping single characters
i++;
if(data.charAt(i) == 'n') currentContent += "\n";
else if(data.charAt(i) == 't') currentContent += "\t";
else if(data.charAt(i) == '\\') currentContent += "\\";
else
currentContent += data.substring(i, i+1);
} else if(includes(openAndClose, thisChar)) {
// If a quote is found
// Toggle value
values[getIndex(openAndClose, thisChar)] = 1 -
values[getIndex(openAndClose, thisChar)];
if(allZero(depths)) {
// If not in array or object
if(values[getIndex(openAndClose, thisChar)] == 1) {
// If start, start string reading
currentType = Types.STRING;
currentContent = "";
} else {
// If end, add data to results
currentType = Types.NONE;
result.add(new String(currentContent));
currentContent = "";
}
} else {
// Add a quote if in an object/array
currentContent += "\"";
}
} else if (!allZero(values)) {
// If in quotes
currentContent += data.substring(i, i+1);
} else if (includes(openChars,thisChar)) {
// If opening bracket
if(allZero(depths)) {
// Start if not in another array/object
if(thisChar == '{') currentType = Types.OBJECT;
if(thisChar == '[') currentType = Types.ARRAY;
currentContent = "";
} else {
// Otherwise, just add to content
currentContent += data.substring(i, i+1);
}
// Increment depths as we go deeper into data
depths[getIndex(openChars, thisChar)]++;
} else if (includes(closeChars,thisChar)) {
// Closing bracket
// Going out of deeper part of data
depths[getIndex(closeChars, thisChar)]--;
if(allZero(depths)) {
// Add data to results
result.add(new JSONObject(currentContent.trim(),
currentType));
currentType = Types.NONE;
currentContent = "";
} else {
currentContent += data.substring(i, i+1);
}
} else if (!allZero(depths)) {
// If in object or array
currentContent += data.substring(i, i+1);
} else if (thisChar == ',') {
// If at a comma
if(!(currentContent.trim().length() > 0)) {
// If nothing, do nothing
continue;
}
// Trim whitespace
currentContent = currentContent.trim();
if(currentContent.equals("true")) {
// true
result.add(true);
} else if(currentContent.equals("false")) {
// false
result.add(false);
} else if(currentContent.equals("null")) {
// null
result.add(null);
} else {
try {
// Try as int
result.add((int)Integer.parseInt(currentContent));
} catch (Exception e) {
try {
// Try as double
result.add((double)Double.parseDouble(currentContent));
} catch (Exception err) {
// Unknown type
System.out.println("Warning: Unknown type");
System.out.println(currentContent);
}
}
}
// Reset
currentContent = "";
} else {
currentContent += data.substring(i, i+1);
}
}
// Process last item in array
if(currentContent.trim().length() > 0) {
currentContent = currentContent.trim();
if(currentContent.equals("true")) {
result.add(true);
} else if(currentContent.equals("false")) {
result.add(false);
} else if(currentContent.equals("null")) {
result.add(null);
} else {
try {
result.add((int)Integer.parseInt(currentContent));
} catch (Exception e) {
try {
result.add((double)Double.parseDouble(currentContent));
} catch (Exception err) {
System.out.println("Warning: Unknown type");
System.out.println(currentContent);
}
}
}
currentContent = "";
}
return result;
}
/**
* Parses an object from a given data between the two curly brackets
*
* @param data the data between the curly brackets
* @return a HashMap of all of the data in the object
**/
private HashMap<String, Object> parseObj(String data) {
/*
* Almost everything is the same as parseArray, so I am not going to
* re-document everything here.
*/
// HashMap instead of ArrayList
HashMap<String, Object> result = new HashMap<String, Object>();
char[] openChars = {'{', '['};
char[] closeChars = {'}', ']'};
char[] openAndClose = {'"'};
int[] depths = {0, 0};
int[] values = {0};
int i = 0;
// We need a key for each parameter of the object
if(data.indexOf(":") == -1) {
return result;
}
String currentKey = data.substring(i, data.indexOf(":", i)).trim();
currentKey = currentKey.substring(1, currentKey.length() - 1);
// Move i to after key
i = data.indexOf(":", i) + 1;
String currentContent = "";
Types currentType = Types.NONE;
for(; i < data.length(); i++) {
char thisChar = data.charAt(i);
if(thisChar == '\\') {
i++;
if(data.charAt(i) == 'n') currentContent += "\n";
else
currentContent += data.substring(i, i+1);
} else if(includes(openAndClose, thisChar)) {
values[getIndex(openAndClose, thisChar)] = 1 -
values[getIndex(openAndClose, thisChar)];
if(allZero(depths)) {
if(values[getIndex(openAndClose, thisChar)] == 1) {
currentType = Types.STRING;
currentContent = "";
} else {
currentType = Types.NONE;
// Notice this is different since we are using
// HashMap instead of ArrayList...
result.put(currentKey, new String(currentContent));
currentContent = "";
}
} else {
currentContent += "\"";
}
} else if (!allZero(values)) {
currentContent += data.substring(i, i+1);
} else if (includes(openChars,thisChar)) {
if(allZero(depths)) {
if(thisChar == '{') currentType = Types.OBJECT;
if(thisChar == '[') currentType = Types.ARRAY;
currentContent = "";
} else {
currentContent += data.substring(i, i+1);
}
depths[getIndex(openChars, thisChar)]++;
} else if (includes(closeChars,thisChar)) {
depths[getIndex(closeChars, thisChar)]--;
if(allZero(depths)) {
result.put(currentKey, new JSONObject(currentContent.trim(),
currentType));
currentType = Types.NONE;
currentContent = "";
} else {
currentContent += data.substring(i, i+1);
}
} else if (!allZero(depths)) {
currentContent += data.substring(i, i+1);
} else if (thisChar == ',') {
if(!(currentContent.trim().length() > 0)) {
// Even if nothing is found in this item, we need a new
// key.
i++;
currentKey = data.substring(i, data.indexOf(":", i)).trim();
currentKey = currentKey.substring(1, currentKey.length() - 1);
i = data.indexOf(":", i);
//System.out.println("New Key: " + currentKey);
currentContent = "";
continue;
}
currentContent = currentContent.trim();
if(currentContent.equals("true")) {
result.put(currentKey, true);
} else if(currentContent.equals("false")) {
result.put(currentKey, false);
} else if(currentContent.equals("null")) {
result.put(currentKey, null);
} else {
try {
result.put(currentKey, (int)Integer.parseInt(currentContent));
} catch (Exception e) {
try {
result.put(currentKey, (double)Double.parseDouble(currentContent));
} catch (Exception err) {
System.out.println("Warning: Unknown type");
System.out.println(currentContent);
}
}
}
// Get new key
i++;
currentKey = data.substring(i, data.indexOf(":", i)).trim();
currentKey = currentKey.substring(1, currentKey.length() - 1);
i = data.indexOf(":", i);
//System.out.println("New Key: " + currentKey);
currentContent = "";
} else {
currentContent += data.substring(i, i+1);
}
}
if(currentContent.trim().length() > 0) {
currentContent = currentContent.trim();
if(currentContent.equals("true")) {
result.put(currentKey, true);
} else if(currentContent.equals("false")) {
result.put(currentKey, false);
} else if(currentContent.equals("null")) {
result.put(currentKey, null);
} else {
try {
result.put(currentKey, (int)Integer.parseInt(currentContent));
} catch (Exception e) {
try {
result.put(currentKey, (double)Double.parseDouble(currentContent));
} catch (Exception err) {
System.out.println("Warning: Unknown type");
System.out.println(currentContent);
}
}
}
}
return result;
}
/**
* Gets if a char array includes a value
*
* @param arr the array
* @param value the value
* @return if value is in array
**/
private boolean includes(char[] arr, char value) {
for(char val : arr) {
if(val == value) return true;
}
return false;
}
/**
* Gets index of value in char array
*
* @param arr the array
* @param value the value
* @return index
**/
private int getIndex(char[] arr, char value) {
for(int i = 0; i < arr.length; i++) {
char val = arr[i];
if(val == value) return i;
}
return -1;
}
/**
* Gets first non-zero index of an int array
*
* @param arr the array
* @return index
**/
private int getNonZeroIndex(int[] arr) {
for(int i = 0; i < arr.length; i++) {
if(arr[i] != 0) return i;
}
return -1;
}
/**
* Gets if an int array is all 0
*
* @param arr the array
* @return if all zero
**/
private boolean allZero(int[] arr) {
for(int i : arr) if(i != 0) return false;
return true;
}
/**
* toString() method
*
* @return data as a String
**/
public String toString() {
if(type == Types.ARRAY) {
String building = "[";
for(Object item : arrData) {
if(!building.equals("[")) {
building += ", ";
}
if(item instanceof String) {
building += "\"" + ((String)item).replace("\\", "\\\\").replace("\n", "\\n").replace("\t", "\\t").replace("\"", "\\\"") + "\"";
} else {
building += item + "";
}
}
building += "]";
return building;
} else {
String building = "{";
for(String key : objData.keySet()) {
if(!building.equals("{")) {
building += ", ";
}
building += "\"" + ((String)key).replace("\\", "\\\\").replace("\n", "\\n").replace("\t", "\\t").replace("\"", "\\\"") + "\": ";
Object item = objData.get(key);
if(item instanceof String) {
building += "\"" + ((String)item).replace("\\", "\\\\").replace("\n", "\\n").replace("\t", "\\t").replace("\"", "\\\"") + "\"";
} else {
building += item + "";
}
}
building += "}";
return building;
}
}
/**
* Gets a key from an object
*
* @param key the key
* @return the value
**/
public Object get(String key) {
if(type == Types.ARRAY) return null;
return objData.get(key);
}
/**
* Sets a key in the object
*
* @param key the key
* @param val the value
**/
public void set(String key, Object val) {
if(type == Types.ARRAY) return;
objData.put(key, val);
}
/**
* Sets an index in the array
*
* @param index the index
* @param val the value
**/
public void set(int index, Object val) {
if(type == Types.OBJECT) return;
arrData.set(index, val);
}
/**
* Adds to the array
*
* @param val the value
**/
public void add(Object val) {
if(type == Types.OBJECT) return;
arrData.add(val);
}
/**
* Adds to the array
*
* @param index the index
* @param val the value
**/
public void add(int index, Object val) {
if(type == Types.OBJECT) return;
arrData.add(index, val);
}
/**
* Gets an index from an array
*
* @param index the index
* @return the value
**/
public Object get(int index) {
if(type == Types.OBJECT) return null;
return arrData.get(index);
}
/**
* Accessor for ArrayList
*
* @return the ArrayList
**/
public ArrayList<Object> getArrayList() {
return arrData;
}
/**
* Accessor for HashMap
*
* @return the HashMap
**/
public HashMap<String, Object> getHashMap() {
return objData;
}
/**
* Create an object of a given class using this data
*
* @param classA the class
* @return the object
**/
public <T> T toObject(Class<T> classA) throws Exception {
// Get constructor
Constructor thisConstructor = getConstructor(1, classA);
// Make constructor accesible - otherwise error
thisConstructor.setAccessible(true);
Object[] params = new Object[0];
if(type == Types.OBJECT) params = new Object[]{objData};
if(type == Types.ARRAY) params = new Object[]{arrData};
return (T)(thisConstructor.newInstance(params));
}
/**
* Get a constructor given a length and a class
*
* @param length the length
* @param classA the class
* @return the constructor
**/
private Constructor getConstructor(int length, Class<?> classA) {
// Get list
Constructor[] list = classA.getDeclaredConstructors();
// Loop through list
for(Constructor current : list) {
// If length matches, return
if(current.getParameterCount() == length) {
return current;
}
}
// No value = null
return null;
}
}