-
Notifications
You must be signed in to change notification settings - Fork 24
/
JSON.java
90 lines (79 loc) · 2.33 KB
/
JSON.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
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.text.ParseException;
/**
* Utilities for our simple implementation of JSON.
*/
public class JSON {
// +---------------+-----------------------------------------------
// | Static fields |
// +---------------+
/**
* The current position in the input.
*/
static int pos;
// +----------------+----------------------------------------------
// | Static methods |
// +----------------+
/**
* Parse a string into JSON.
*/
public static JSONValue parse(String source) throws ParseException, IOException {
return parse(new StringReader(source));
} // parse(String)
/**
* Parse a file into JSON.
*/
public static JSONValue parseFile(String filename) throws ParseException, IOException {
FileReader reader = new FileReader(filename);
JSONValue result = parse(reader);
reader.close();
return result;
} // parseFile(String)
/**
* Parse JSON from a reader.
*/
public static JSONValue parse(Reader source) throws ParseException, IOException {
pos = 0;
JSONValue result = parseKernel(source);
if (-1 != skipWhitespace(source)) {
throw new ParseException("Characters remain at end", pos);
}
return result;
} // parse(Reader)
// +---------------+-----------------------------------------------
// | Local helpers |
// +---------------+
/**
* Parse JSON from a reader, keeping track of the current position
*/
static JSONValue parseKernel(Reader source) throws ParseException, IOException {
int ch;
ch = skipWhitespace(source);
if (-1 == ch) {
throw new ParseException("Unexpected end of file", pos);
}
// STUB
throw new ParseException("Unimplemented", pos);
} // parseKernel
/**
* Get the next character from source, skipping over whitespace.
*/
static int skipWhitespace(Reader source) throws IOException {
int ch;
do {
ch = source.read();
++pos;
} while (isWhitespace(ch));
return ch;
} // skipWhitespace(Reader)
/**
* Determine if a character is JSON whitespace (newline, carriage return,
* space, or tab).
*/
static boolean isWhitespace(int ch) {
return (' ' == ch) || ('\n' == ch) || ('\r' == ch) || ('\t' == ch);
} // isWhiteSpace(int)
} // class JSON