寒假写了个 JSON 解析器

一个 JSON 解析器

使用方法:

1
2
3
4
5
6
7
8
9
string data = File.ReadAllText(@"f:\1.Json");
dynamic obj = Json.Parse(data);

Console.WriteLine(obj.employees[0].firstName);

foreach (var it in obj.employees)
{
Console.WriteLine(it.lastName);
}

假设 json 文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"employees": [
{
"firstName": "Bill",
"lastName": "Gates"
},
{
"firstName": "George",
"lastName": "Bush"
},
{
"firstName": "Thomas",
"lastName": "Carter"
}
]
}

使用了 c#4.0 的动态特性, c# 越来越像动态语言了, 用着真舒服.
代码如下, 就是个递归下降:

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Dynamic;

namespace Json
{
public class Json
{
private class JsonObject : DynamicObject
{
public JsonObject(Dictionary<string, dynamic> member)
{
this.member = member;
}

public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (member.ContainsKey(binder.Name))
{
result = member[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}

private Dictionary<string, dynamic> member;
}

private static int CharToInt(char c)
{
switch (c)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
}
throw new Exception("c不是一个数字字符");
}

private enum TokenType
{
LBrace, RBrace,
LBracket, RBracket,
Colon, Comma,
True, False,
Null, String,
Number
}

private struct Token
{
public TokenType type;
public dynamic value;
}

private enum NumberState
{
Start, MinusRead, ZeroRead, InInt, DotRead, InFraction, ERead, InExponent, End
}

private static Token GetToken(string json, ref int i)
{
while (i < json.Length && char.IsWhiteSpace(json[i]))
i++;

Token token = new Token();
string sub = json.Substring(i);

if (json[i] == '{')
{
token.type = TokenType.LBrace;
i = i + 1;
}
else if (json[i] == '}')
{
token.type = TokenType.RBrace;
i = i + 1;
}
else if (json[i] == '[')
{
token.type = TokenType.LBracket;
i = i + 1;
}
else if (json[i] == ']')
{
token.type = TokenType.RBracket;
i = i + 1;
}
else if (json[i] == ':')
{
token.type = TokenType.Colon;
i = i + 1;
}
else if (json[i] == ',')
{
token.type = TokenType.Comma;
i = i + 1;
}
else if (sub.StartsWith("true"))
{
token.type = TokenType.True;
i = i + 4;
}
else if (sub.StartsWith("false"))
{
token.type = TokenType.False;
i = i + 4;
}
else if (sub.StartsWith("null"))
{
token.type = TokenType.Null;
i = i + 4;
}
else if (json[i] == '"') //string
{
StringBuilder sb = new StringBuilder();
i++;

while (i < json.Length)
{
int len = 0;
while (i + len < json.Length && json[i + len] != '"' && json[i + len] != '\\')
len++;

sb.Append(json.Substring(i, len));

if (i + len >= json.Length)
{
throw new Exception("未找到匹配的引号");
}
else if (json[i + len] == '"')
{
i += len + 1;
break;
}

i += len + 1;
switch (json[i])
{
case '"':
sb.Append('"');
i++;
break;
case '\\':
sb.Append('\\');
i++;
break;
case '/':
sb.Append('/');
i++;
break;
case 'b':
sb.Append('\b');
i++;
break;
case 'f':
sb.Append('\f');
i++;
break;
case 'n':
sb.Append('\n');
i++;
break;
case 'r':
sb.Append('\r');
i++;
break;
case 't':
sb.Append('\t');
i++;
break;
case 'u':
string hex = json.Substring(i + 1, 4);
ushort code = Convert.ToUInt16(hex, 16);
char c = (char)code;
sb.Append(c);
i += 5;
break;
}
}

token.value = sb.ToString();
token.type = TokenType.String;
}
else if (json[i] == '-' || char.IsNumber(json[i])) //nubmer
{
dynamic value = 0;
bool isMinus = false;
int frac = 10;
bool isExponentNegative = false;
int exponent = 0;

NumberState state = NumberState.Start;

while (state != NumberState.End)
{
switch (state)
{
case NumberState.Start:
if (json[i] == '-')
{
isMinus = true;

state = NumberState.MinusRead;
}
else if (json[i] == '0')
{
state = NumberState.ZeroRead;
}
else if (char.IsNumber(json[i]))
{
value = CharToInt(json[i]);
state = NumberState.InInt;
}
else
{
throw new Exception("不能识别的字符‘" + json[i] + "’");
}
i++;
break;
case NumberState.MinusRead:
if (json[i] == '0')
{
state = NumberState.ZeroRead;
}
else if (char.IsNumber(json[i]))
{
value = CharToInt(json[i]);
state = NumberState.InInt;
}
else
{
throw new Exception("不能识别的字符‘" + json[i] + "’");
}
i++;
break;
case NumberState.InInt:
if (char.IsNumber(json[i]))
{
value *= 10;
value += CharToInt(json[i]);
}
else if (json[i] == '.')
{
state = NumberState.DotRead;
}
else if (json[i] == 'e' || json[i] == 'E')
{
state = NumberState.ERead;
}
else
{
i--;
state = NumberState.End;
}
i++;
break;
case NumberState.ZeroRead:
if (json[i] == '.')
{
state = NumberState.DotRead;
}
else if (json[i] == 'e' || json[i] == 'E')
{
state = NumberState.ERead;
}
else
{
i--;
state = NumberState.End;
}
i++;
break;
case NumberState.DotRead:
if (char.IsNumber(json[i]))
{
value += (double)CharToInt(json[i]) / frac;
frac *= 10;
state = NumberState.InFraction;
}
else
{
throw new Exception("不能识别的字符‘" + json[i] + "’");
}
i++;
break;
case NumberState.InFraction:
if (char.IsNumber(json[i]))
{
value += (double)CharToInt(json[i]) / frac;
frac *= 10;
}
else if (json[i] == 'e' || json[i] == 'E')
{
state = NumberState.ERead;
}
else
{
i--;
state = NumberState.End;
}
i++;
break;
case NumberState.ERead:
if (char.IsNumber(json[i]))
{
exponent = CharToInt(json[i]);
state = NumberState.InExponent;
}
else if (json[i] == '+')
{
state = NumberState.InExponent;
}
else if (json[i] == '-')
{
isExponentNegative = true;
state = NumberState.InExponent;
}
else
{
throw new Exception("不能识别的字符‘" + json[i] + "’");
}
i++;
break;
case NumberState.InExponent:
if (char.IsNumber(json[i]))
{
exponent *= 10;
exponent = CharToInt(json[i]);
}
else
{
i--;
state = NumberState.End;
}
i++;
break;
}
if (i >= json.Length)
state = NumberState.End;
}

if (exponent != 0)
{
if (isExponentNegative)
{
value = value * Math.Pow(10, -exponent);
}
else
{
value = value * Math.Pow(10, exponent);
}
}
if (isMinus)
token.value = -value;
else
token.value = value;
token.type = TokenType.Number;

}
else
throw new Exception("不能识别的字符‘" + json[i] + "’");

while (i < json.Length && char.IsWhiteSpace(json[i]))
i++;
return token;
}

private static dynamic Value(string json, ref int i)
{
Token token = GetToken(json, ref i);
if (token.type == TokenType.Null)
return null;
else if (token.type == TokenType.False)
return false;
else if (token.type == TokenType.True)
return true;
else if (token.type == TokenType.Number)
return token.value;
else if (token.type == TokenType.String)
return token.value;
else if (token.type == TokenType.LBrace)
{
Dictionary<string, dynamic> member = new Dictionary<string, dynamic>();

bool first = true;
while (true)
{
if (first)
{
int tmpi = i;
token = GetToken(json, ref i);
if (token.type == TokenType.RBrace)
break;
else
i = tmpi;

first = false;
}

token = GetToken(json, ref i);
if (token.type != TokenType.String)
{
throw new Exception("出乎意料的Token: " + token.type);
}
string name = token.value;

token = GetToken(json, ref i);
if (token.type != TokenType.Colon)
{
throw new Exception("出乎意料的Token: " + token.type);
}

dynamic val = Value(json, ref i);
member[name] = val;

token = GetToken(json, ref i);
if (token.type == TokenType.Comma)
continue;
else if (token.type == TokenType.RBrace)
break;
else
throw new Exception("出乎意料的Token: " + token.type);
}

return new JsonObject(member);
}
else if (token.type == TokenType.LBracket)
{
List<dynamic> list = new List<dynamic>();
bool first = true;
while (true)
{
if (first)
{
int tmpi = i;
token = GetToken(json, ref i);
if (token.type == TokenType.RBracket)
break;
else
i = tmpi;

first = false;
}

list.Add(Value(json, ref i));
token = GetToken(json, ref i);
if (token.type == TokenType.Comma)
continue;
else if (token.type == TokenType.RBracket)
break;
else
throw new Exception("出乎意料的Token: " + token.type);
}
return list.ToArray();
}
else
{
throw new Exception("出乎意料的Token: " + token.type);
}
}

public static dynamic Parse(string json)
{
int i = 0;
return Value(json, ref i);
}
}
}

Proudly powered by Hexo and Theme by Hacker
© 2021 wastecat