-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJson.cs
400 lines (389 loc) · 12.4 KB
/
Json.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MiniJson
{
/* Json is a minimal JSON implementation
* It offers 2 static functions: Stringify & Parse
* Parse converts a valid Json string to an object
* On failure, it will throw a FormatException
* Validation is not absolute; it'll parse "null1234" as null
* Stringify converts an object to Json
* On failure, it will throw an ArgumentException
* Objects are of type double, string, List<object>, Dictionary<string, object>, bool, or null
* */
public static class Json
{
private static int skipWhitespace(string str, int idx)
{
while (char.IsWhiteSpace(str[idx]))
{
idx += 1;
}
return idx;
}
private static object ParseValue(string str, ref int idx)
{
idx = skipWhitespace(str, idx);
var ch = str[idx];
if (ch == '{')
{
idx += 1;
return ParseObject(str, ref idx);
}
else if (ch == '[')
{
idx += 1;
return ParseArray(str, ref idx);
}
else if (ch == '"')
{
idx += 1;
return ParseString(str, ref idx);
}
else if ((ch >= '0' && ch <= '9') || ch == '-')
{
return ParseNumber(str, ref idx);
}
else if (str.Substring(idx, 4) == "null")
{
idx += 4;
return null;
}
else if (str.Substring(idx, 4) == "true")
{
idx += 4;
return true;
}
else if (str.Substring(idx, 5) == "false")
{
idx += 5;
return false;
}
else
{
throw new FormatException("Unknown value @ " + idx);
}
}
private static Dictionary<string, object> ParseObject(string str, ref int idx)
{
var ret = new Dictionary<string, object>();
idx = skipWhitespace(str, idx);
if (str[idx] == '}')
{
idx += 1;
return ret;
}
while (true)
{
if (str[idx] != '"')
{
throw new FormatException("Object expected string @ " + idx);
}
idx += 1;
var key = ParseString(str, ref idx);
idx = skipWhitespace(str, idx);
if (str[idx] != ':')
{
throw new FormatException("Object expected ':' @ " + idx);
}
idx = skipWhitespace(str, idx + 1);
var val = ParseValue(str, ref idx);
ret[key] = val;
idx = skipWhitespace(str, idx);
if (str[idx] == ',')
{
idx = skipWhitespace(str, idx + 1);
}
else if (str[idx] != '}')
{
throw new FormatException("Object expected ',' or '}' @ " + idx);
}
else
{
idx += 1;
return ret;
}
}
}
private static List<object> ParseArray(string str, ref int idx)
{
var ret = new List<object>();
idx = skipWhitespace(str, idx);
if (str[idx] == ']')
{
idx += 1;
return ret;
}
while (true)
{
ret.Add(ParseValue(str, ref idx));
idx = skipWhitespace(str, idx);
if (str[idx] == ',')
{
idx = skipWhitespace(str, idx + 1);
}
else if (str[idx] != ']')
{
throw new FormatException("Array expected ',' or ']'");
}
else
{
idx += 1;
return ret;
}
}
}
private static int chr2hexval(char ch)
{
if (ch >= '0' && ch <= '9')
{
return ch - '0';
}
else if (ch >= 'a' && ch <= 'f')
{
return (ch - 'a') + 10;
}
else if (ch >= 'A' && ch <= 'F')
{
return (ch - 'A') + 10;
}
else
{
return -1;
}
}
private static string ParseString(string str, ref int idx)
{
var sb = new StringBuilder();
while (str[idx] != '"')
{
var ch = str[idx];
if (ch == '\\')
{
var c2 = str[idx + 1];
if (c2 == '"' || c2 == '/' || c2 == '\\') sb.Append(c2);
else if (c2 == 'n') sb.Append('\n');
else if (c2 == 't') sb.Append('\t');
else if (c2 == 'r') sb.Append('\r');
else if (c2 == 'f') sb.Append('\f');
else if (c2 == 'b') sb.Append('\b');
else
{
var hex4 = str.Substring(idx + 1, 4);
if (hex4.Length != 4)
{
throw new FormatException("Unicode escape not length 4");
}
var code = chr2hexval(str[idx + 2]) << 12 | chr2hexval(str[idx + 3]) << 8 | chr2hexval(str[idx + 4]) << 4 | chr2hexval(str[idx + 5]);
if (code < 0 || code > 0xffff)
{
throw new FormatException("Invalid hexadecimal character");
}
sb.Append((char)code);
idx += 6;
continue;
}
idx += 2;
}
else
{
sb.Append(ch);
idx += 1;
}
}
idx += 1;
return sb.ToString();
}
private static double ParseNumber(string str, ref int idx)
{
var ch = str[idx];
bool neg;
double result = 0;
if (ch == '-')
{
neg = true;
idx += 1;
ch = str[idx];
}
else
{
neg = false;
}
if (ch == '0')
{
idx += 1;
if (idx == str.Length || str[idx] != '.')
{
return 0;
}
ch = '.';
}
else if (ch >= '1' && ch <= '9')
{
do
{
result = result * 10 + (ch - '0');
idx += 1;
if (idx == str.Length) return neg ? -result : result;
ch = str[idx];
} while (ch >= '0' && ch <= '9');
}
else
{
throw new FormatException("Expected digit @ " + idx);
}
if (ch == '.')
{
idx += 1;
ch = str[idx];
double nth = 0.0;
while (ch >= '0' && ch <= '9')
{
nth++;
result += (ch - '0') / Math.Pow(10, nth);
idx += 1;
if (idx == str.Length) return neg ? -result : result;
ch = str[idx];
}
if (nth == 0.0)
{
throw new FormatException("Decimal followed by no digits @ idx");
}
}
if (ch == 'e' || ch == 'E')
{
idx += 1;
ch = str[idx];
if ((ch < '0' || ch > '9') && ch != '+' && ch != '-')
{
throw new FormatException("Exponential not followed by digits or + or -");
}
var expneg = ch == '-';
if (ch == '-' || ch == '+')
{
idx += 1;
ch = str[idx];
if (ch < '0' || ch > '9')
{
throw new FormatException("Exponential not followed by digits");
}
}
int exp = 0;
while (ch >= '0' && ch <= '9')
{
exp = exp * 10 + (ch - '0');
idx += 1;
if (idx == str.Length) break;
ch = str[idx];
}
result *= Math.Pow(10, (expneg ? -exp : exp));
}
return neg ? -result : result;
}
private static StringBuilder StringifyString(string str, StringBuilder sb)
{
sb.EnsureCapacity(sb.Length + str.Length + 2);
sb.Append('"');
foreach (var c in str)
{
var substr = c == '"' ? "\\\"" :
c == '\\' ? "\\\\" :
c == '\n' ? "\\n" :
c == '\b' ? "\\b" :
c == '\f' ? "\\f" :
c == '\r' ? "\\r" :
c == '\t' ? "\\t" :
c < ' ' ? "\\u" + ((int)c).ToString("X4") : null;
if (substr != null)
{
sb.Append(substr);
}
else
{
sb.Append(c);
}
}
return sb.Append('"');
}
public static object Parse(string json)
{
try
{
var idx = 0;
return ParseValue(json, ref idx);
}
catch (IndexOutOfRangeException ex)
{
throw new FormatException("Unexpected end of input", ex);
}
}
private static StringBuilder Stringify(object obj, StringBuilder sb)
{
if (obj == null) return sb.Append("null");
var oty = obj.GetType();
if (oty == typeof(string))
{
return StringifyString((string)obj, sb);
}
if (oty == typeof(double))
{
var val = (double)obj;
if (!double.IsNaN(val) && !double.IsInfinity(val))
{
return sb.Append(val.ToString());
}
}
if (oty == typeof(bool))
{
return sb.Append((bool)obj ? "true" : "false");
}
if (oty == typeof(List<object>))
{
var list = (List<object>)obj;
if (list.Count == 0)
{
return sb.Append("[]");
}
else
{
sb.Append('[');
foreach (var listobj in list)
{
Stringify(listobj, sb);
sb.Append(',');
}
sb[sb.Length - 1] = ']';
return sb;
}
}
if (oty == typeof(Dictionary<string, object>))
{
var dict = (Dictionary<string, object>)obj;
if (dict.Count == 0)
{
return sb.Append("{}");
}
else
{
sb.Append('{');
foreach (var kv in dict)
{
StringifyString(kv.Key, sb);
sb.Append(':');
Stringify(kv.Value, sb);
sb.Append(',');
}
sb[sb.Length - 1] = '}';
return sb;
}
}
throw new ArgumentException("Object not JSON convertible");
}
public static string Stringify(object obj)
{
return Stringify(obj, new StringBuilder()).ToString();
}
}
}