JSON的语法简单,很适合上完编译原理课程之后或者学习完龙书语法分析之后的练手。
JSON格式
1 | {"a" : 123 } |
基础为以上几种。有了基本的格式,可以考虑先写词法分析部分。JSON格式类似于key/value存储,其中key为string类型,value复杂一些,可包括,string,int,double,jsonobject,jsonarray,true,false,null标记。所以对每个token都要逐一分析,构造出DFA。
字符串
字符串以 “ 开头,以 “ 结束。其中需要考虑的是转义字符的忽略以及unicode的格式(\u hex hex hex hex)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
37private Token readString() throws IOException, JsonLexException {
StringBuilder builder = new StringBuilder();
while ( (this.at_ = read()) != '\"') {
if (this.at_ == '\r' || this.at_ == '\n') error("string", this.at_);
if (this.at_ == '\\') {
//check escape char
this.at_ = read();
if (isEscapeChar(this.at_)) {
builder.append('\\');
builder.append((char) this.at_);
} else if (this.at_ == 'u'){
//unicode
builder.append('\\');
builder.append('u');
builder.append(unicode());
} else {
error("string", this.at_);
}
} else {
builder.append((char) this.at_);
}
}
if ( this.at_ != '\"') {
//string is not closed
error("string[not closed]", this.at_);
}
return this.token_ = new Token(JsonToken.STRING, new Value(builder.toString()));
}
private String unicode() throws IOException, JsonLexException {
StringBuilder builder = new StringBuilder();
int i=0;
for (;i<4 && isHexChar(this.at_ = read()); builder.append((char) this.at_),++i);
if (i < 4) error("unicode", this.at_);
return builder.toString();
}数字
数字包含有符号int double以及科学计数法表示稍微麻烦,但是画出DFA分析就会明了很多。
据此就可很快写出来。
1 | private Token readNumber(int at) throws IOException,JsonLexException { |
- 其他字符
对于其他终结符,true false null则只要匹配首字符来判断就可以了。
综上就可写出来lexer了
1 | public Token scan() throws IOException, JsonLexException { |
obj -> { members }
members -> pair members’ | eps
members’ -> , pair members’ | eps
pair -> string : value
array -> [ elem ]
elem -> value elem’ | eps
elem’ -> , value elem’ | eps
value -> obj | array | number | string | true | false | null
1 | 求出FIRST集和FOLLOW集,验证可知为LL(1)文法。这样就可以用递归下降来做语法分析。 |
至此一个简单的解析器已经写完了,只是实现了简单的解析功能,一个完善的JAVA JSON解析器至少可以对对象序列化和反序列化。后续将会添加上这部分功能,再更新一遍 :-|
源代码:ToyJSON