-
Notifications
You must be signed in to change notification settings - Fork 0
/
json-serializer-deserializer.cs
398 lines (348 loc) · 8.64 KB
/
json-serializer-deserializer.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
// This is the short, one-file version of Json Parser (By JpRichardson, https://github.com/jprichardson/FridayThe13th)
// * Also, this file is with inline references to avoid "using" tags.
namespace FridayThe13th
{
public class JsonParser
{
public string author() { return "https://github.com/jprichardson/FridayThe13th"; }
private int _line = 0;
private int _column = 0;
private string _jsonText = "";
private int _index = 0;
private System.Text.StringBuilder _sb = new System.Text.StringBuilder();
public JsonParser() { CamelizeProperties = false; ExceptionOnParsingError = false; }
public bool CamelizeProperties { get; set; }
public bool ExceptionOnParsingError { get; set; }
public int ErrorCount { get { return _errorMessages.Count; } }
private System.Collections.Generic.List<string> _errorMessages = new System.Collections.Generic.List<string>();
public System.Collections.Generic.IEnumerable<string> ErrorMessages { get { return _errorMessages; } }
public dynamic Parse(string json)
{
Reset();
_jsonText = json;
return ParseValue();
}
public void Reset()
{
_index = _line = _column = 0;
_errorMessages.Clear();
_jsonText = "";
}
protected System.Collections.Generic.List<dynamic> ParseArray()
{
Read(); //read first [
var list = new System.Collections.Generic.List<dynamic>();
var doRead = true;
while (doRead)
{
ReadWhitespace();
switch (Peek())
{
case -1: ParseError("Unterminated array before end of json string."); return list;
case ',':
Read();
break;
case ']':
Read();
doRead = false;
break;
default:
var val = ParseValue();
list.Add(val);
break;
}
}
return list;
}
protected dynamic ParseObject()
{
Read(); //read first {
ReadWhitespace();
dynamic obj = new JsonObject();
var doRead = true;
while (doRead)
{
switch (Peek())
{
case -1: ParseError("Unterminated object before end of json string."); return obj;
case ',':
Read();
break;
case '}':
Read();
doRead = false;
break;
case '"':
var key = ParseString();
if (CamelizeProperties)
{
_sb.Clear();
if (key.Contains("_"))
{
var words = key.Split('_');
foreach (var w in words)
{
_sb.Append(w.Substring(0, 1).ToUpper());
_sb.Append(w.Substring(1, w.Length - 1).ToLower());
}
}
else
{
_sb.Append(key.Substring(0, 1).ToUpper());
_sb.Append(key.Substring(1, key.Length - 1).ToLower());
}
key = _sb.ToString();
}
ReadWhitespace();
ReadExpect(':');
ReadWhitespace();
var val = ParseValue();
obj[key] = val;
break;
default:
ReadWhitespace();
break;
}
}
return obj;
}
//not very robust.... yet
////http://ecma262-5.com/ELS5_HTML.htm#Section_8.5
protected double ParseNumber()
{
_sb.Clear();
bool doRead = true;
while (doRead)
{
var c = Peek();
switch (c)
{
case '.':
case '-':
case '+':
case 'e':
case 'E':
_sb.Append((char)c);
Read();
doRead = true;
break;
default:
if (c >= '0' && c <= '9')
{
_sb.Append((char)c);
Read();
doRead = true;
}
else
doRead = false;
break;
}
}
double number;
bool couldParse = System.Double.TryParse(_sb.ToString(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out number);
if (!couldParse)
{
number = System.Double.NaN;
ParseError(string.Format("Could not parse {0} into a Double.", number));
}
return number;
}
protected string ParseString()
{
Read(); //read first "
_sb.Clear();
bool complete = false;
while (!complete)
{
var c = Read();
switch (c)
{
case -1: ParseError("Unterminated string before end of json string."); return _sb.ToString();
case '"': complete = true; break;
case '\\':
var nc = Read();
switch (nc)
{
case '"':
case '\\':
case '/':
_sb.Append((char)nc);
break;
case 'b':
_sb.Append('\b');
break;
case 'f':
_sb.Append('\f');
break;
case 'n':
_sb.Append('\n');
break;
case 'r':
_sb.Append('\r');
break;
case 't':
_sb.Append('\t');
break;
case 'u':
ushort cp = 0;
for (int i = 0; i < 4; i++)
{
if ((c = Read()) < 0)
ParseError("Incomplete unicode.");
cp *= 16;
if ('0' <= c && c <= '9')
cp += (ushort)(c - '0');
if ('A' <= c && c <= 'F')
cp += (ushort)(c - 'A' + 10);
if ('a' <= c && c <= 'f')
cp += (ushort)(c - 'a' + 10);
}
_sb.Append((char)cp);
break;
}
break;
default:
_sb.Append((char)c);
break;
}
}
return _sb.ToString();
}
protected dynamic ParseValue()
{
ReadWhitespace();
var c = Peek();
switch (c)
{
case -1: ParseError("Unknown parsing error. Premature end of json string."); return null;
case '{': return ParseObject();
case '"': return ParseString();
case '[': return ParseArray();
case '-': return ParseNumber();
case 't': if (TryRead("true")) { return true; } else { goto default; }
case 'f': if (TryRead("false")) { return false; } else { goto default; }
case 'n': if (TryRead("null")) { return null; } else { goto default; }
default:
if (c >= '0' && c <= '9')
return ParseNumber();
else
{
ParseError("Unrecognized JSON character token.");
Read(); //get rid of bad character, go to next
return ParseValue();
}
}
}
protected int Peek()
{
if (_index == _jsonText.Length)
return -1; //EOF
else
return _jsonText[_index];
}
protected int Read()
{
if (_index == _jsonText.Length)
return -1;
else
{
int c = _jsonText[_index++];
if (c == '\n')
{
_line++;
_column = 0;
}
else
_column++;
return c;
}
}
protected void ReadExpect(char c)
{
var expect = Read();
if (expect == -1)
ParseError(string.Format("Expected {0} but is at the end of the string.", c));
else
if (expect != c)
ParseError(string.Format("Expected {0} but received {1}.", c, expect));
}
protected void ReadWhitespace()
{
bool doRead = true;
while (doRead)
{
switch (Peek())
{
case ' ':
case '\t':
case '\r':
case '\n':
Read();
break;
default: doRead = false; break;
}
}
}
protected bool TryRead(string s)
{
bool success = true;
for (var i = 0; i < s.Length; ++i)
if (s[i] != Read())
{
_index = _index - i - 1;
success = false;
break;
}
return success;
}
protected void ParseError(string msg)
{
msg = string.Format("{0} ({1},{2})", msg, _line, _column);
if (ExceptionOnParsingError)
throw new System.Exception(msg);
else
_errorMessages.Add(msg);
}
}
public class JsonObject : System.Dynamic.DynamicObject, System.ComponentModel.INotifyPropertyChanged
{
protected System.Collections.Generic.Dictionary<string, dynamic> _thisDict;
public JsonObject()
{
_thisDict = new System.Collections.Generic.Dictionary<string, dynamic>();
}
public bool IsEmpty { get { return _thisDict.Count == 0; } }
public System.Collections.Generic.IEnumerable<string> Keys { get { return _thisDict.Keys; } }
public System.Collections.Generic.IEnumerable<dynamic> Values { get { return _thisDict.Values; } }
public dynamic this[string key] { get { return _thisDict[key]; } set { _thisDict[key] = value; NotifyPropertyChanged(key); } }
public void Add(string key, dynamic value)
{
_thisDict.Add(key, value);
NotifyPropertyChanged(key);
}
public bool Remove(string key)
{
return _thisDict.Remove(key);
}
public void RemoveAll()
{
_thisDict.Clear();
}
public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
{
return _thisDict.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value)
{
_thisDict[binder.Name] = value;
NotifyPropertyChanged(binder.Name);
return true;
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}