Source

Manatee.Json / Json / JsonValue.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
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/***************************************************************************************

	Copyright 2012 Greg Dennis

	   Licensed under the Apache License, Version 2.0 (the "License");
	   you may not use this file except in compliance with the License.
	   You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

	   Unless required by applicable law or agreed to in writing, software
	   distributed under the License is distributed on an "AS IS" BASIS,
	   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	   See the License for the specific language governing permissions and
	   limitations under the License.
 
	File Name:		JsonValue.cs
	Namespace:		Manatee.Json
	Class Name:		JsonValue
	Purpose:		Represents a JSON value.

***************************************************************************************/
using System;
using System.Globalization;
using Manatee.Json.Enumerations;
using Manatee.Json.Exceptions;

namespace Manatee.Json
{
	/// <summary>
	/// Represents a JSON value.
	/// </summary>
	/// <remarks>
	/// A value can consist of a string, a numerical value, a boolean (true or false), a null
	/// placeholder, a JSON array of values, or a nested JSON object.
	/// </remarks>
	public class JsonValue
	{
		private const string EscapeChars = @"\""/bfnrtu";

		private const string TypeableChars =
			@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 `-=,./;'[]\~!@#$%^&*()_+<>?:\""{}|";

		bool boolValue = false;
		string stringValue = null;
		double numberValue = 0;
		JsonObject objectValue = null;
		JsonArray arrayValue = null;

		/// <summary>
		/// Globally defined null-valued JSON value.
		/// </summary>
		/// <remarks>
		/// Use this when initializing a JSON object or array.
		/// </remarks>
		public readonly static JsonValue Null = new JsonValue();

		/// <summary>
		/// Accesses the JsonValue as a boolean.
		/// </summary>
		/// <exception cref="JsonValueIncorrectTypeException">
		/// Thrown when this JsonValue does not contain a boolean.
		/// </exception>
		/// <remarks>
		/// Setting the value as a boolean will automatically change the JsonValue's type and
		/// discard the old data.
		/// </remarks>
		public bool Boolean
		{
			get
			{
				if (Type != JsonValueType.Boolean)
					throw new JsonValueIncorrectTypeException(Type, JsonValueType.Boolean);
				return boolValue;
			}
			private set
			{
				Type = JsonValueType.Boolean;
				boolValue = value;
			}
		}
		/// <summary>
		/// Accesses the JsonValue as a string.
		/// </summary>
		/// <exception cref="JsonValueIncorrectTypeException">
		/// Thrown when this JsonValue does not contain a string.
		/// </exception>
		/// <remarks>
		/// Setting the value as a string will automatically change the JsonValue's type and
		/// discard the old data.
		/// </remarks>
		public string String
		{
			get
			{
				if (Type != JsonValueType.String)
					throw new JsonValueIncorrectTypeException(Type, JsonValueType.String);
				return stringValue;
			}
			private set
			{
				Type = JsonValueType.String;
				stringValue = value;
			}
		}
		/// <summary>
		/// Accesses the JsonValue as a numeric value.
		/// </summary>
		/// <exception cref="JsonValueIncorrectTypeException">
		/// Thrown when this JsonValue does not contain a numeric value.
		/// </exception>
		/// <remarks>
		/// Setting the value as a numeric value will automatically change the JsonValue's type and
		/// discard the old data.
		/// </remarks>
		public double Number
		{
			get
			{
				if (Type != JsonValueType.Number)
					throw new JsonValueIncorrectTypeException(Type, JsonValueType.Number);
				return numberValue;
			}
			private set
			{
				Type = JsonValueType.Number;
				numberValue = value;
			}
		}
		/// <summary>
		/// Accesses the JsonValue as a JSON object.
		/// </summary>
		/// <exception cref="JsonValueIncorrectTypeException">
		/// Thrown when this JsonValue does not contain a Json object.
		/// </exception>
		/// <remarks>
		/// Setting the value as a Json object will automatically change the JsonValue's type and
		/// discard the old data.
		/// </remarks>
		public JsonObject Object
		{
			get
			{
				if (Type != JsonValueType.Object)
					throw new JsonValueIncorrectTypeException(Type, JsonValueType.Object);
				return objectValue;
			}
			private set
			{
				Type = JsonValueType.Object;
				objectValue = value;
			}
		}
		/// <summary>
		/// Accesses the JsonValue as a JSON array.
		/// </summary>
		/// <exception cref="JsonValueIncorrectTypeException">
		/// Thrown when this JsonValue does not contain a Json array.
		/// </exception>
		/// <remarks>
		/// Setting the value as a Json array will automatically change the JsonValue's type and
		/// discard the old data.
		/// </remarks>
		public JsonArray Array
		{
			get
			{
				if (Type != JsonValueType.Array)
					throw new JsonValueIncorrectTypeException(Type, JsonValueType.Array);
				return arrayValue;
			}
			private set
			{
				Type = JsonValueType.Array;
				arrayValue = value;
			}
		}
		/// <summary>
		/// Gets the value type of the existing data.
		/// </summary>
		public JsonValueType Type { get; private set; }

		/// <summary>
		/// Creates a null JsonValue.
		/// </summary>
		public JsonValue()
		{
			Type = JsonValueType.Null;
		}
		/// <summary>
		/// Creates a JsonValue from a boolean.
		/// </summary>
		public JsonValue(bool b)
		{
			Boolean = b;
		}
		/// <summary>
		/// Creates a JsonValue from a string.
		/// </summary>
		public JsonValue(string s)
		{
			String = s;
		}
		/// <summary>
		/// Creates a JsonValue from a numeric value.
		/// </summary>
		public JsonValue(double n)
		{
			Number = n;
		}
		/// <summary>
		/// Creates a JsonValue from a JSON object.
		/// </summary>
		public JsonValue(JsonObject o)
		{
			Object = o;
		}
		/// <summary>
		/// Creates a JsonValue from a JSON array.
		/// </summary>
		public JsonValue(JsonArray a)
		{
			Array = a;
		}

		/// <summary>
		/// Creates a string representation of the JSON data.
		/// </summary>
		/// <param name="indentLevel">The indention level for the value.</param>
		/// <returns>A string.</returns>
		public string GetIndentedString(int indentLevel = 0)
		{
			switch (Type)
			{
				case JsonValueType.Object:
					return objectValue.GetIndentedString(indentLevel);
				case JsonValueType.Array:
					return arrayValue.GetIndentedString(indentLevel);
				default:
					return "null";
			}
		}

		/// <summary>
		/// Creates a string that represents this JsonValue.
		/// </summary>
		/// <returns>A string representation of this JsonValue.</returns>
		/// <remarks>
		/// Passing the returned string back into the parser will result in a copy of
		/// this JsonValue.
		/// </remarks>
		public override string ToString()
		{
			switch (Type)
			{
				case JsonValueType.Number:
					return string.Format("{0}", numberValue);
				case JsonValueType.String:
					return string.Format("\"{0}\"", InsertEscapeSequences(stringValue));
				case JsonValueType.Boolean:
					return boolValue ? "true" : "false";
				case JsonValueType.Object:
					return string.Format("{0}", objectValue);
				case JsonValueType.Array:
					return string.Format("{0}", arrayValue);
				default:
					return "null";
			}
		}
		/// <summary>
		/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
		/// </summary>
		/// <returns>
		/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
		/// </returns>
		/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>. </param><filterpriority>2</filterpriority>
		public override bool Equals(object obj)
		{
			var json = obj as JsonValue;
			if (json == null) return false;
			if (json.Type != Type) return false;
			switch (Type)
			{
				case JsonValueType.Number:
					return Number.Equals(json.Number);
				case JsonValueType.String:
					return String.Equals(json.String);
				case JsonValueType.Boolean:
					return Boolean.Equals(json.Boolean);
				case JsonValueType.Object:
					return Object.Equals(json.Object);
				case JsonValueType.Array:
					return Array.Equals(json.Array);
				case JsonValueType.Null:
					return true;
			}
			return false;
		}
		/// <summary>
		/// Serves as a hash function for a particular type. 
		/// </summary>
		/// <returns>
		/// A hash code for the current <see cref="T:System.Object"/>.
		/// </returns>
		/// <filterpriority>2</filterpriority>
		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		/// <summary>
		/// Parses a string containing a JSON value.
		/// </summary>
		/// <param name="source">the string to parse.</param>
		/// <returns>The JSON value represented by the string.</returns>
		public static JsonValue Parse(string source)
		{
			var i = 1;
			return Parse(StripExternalSpaces(source), ref i);
		}

		/// <summary>
		/// Implicitly converts a boolean into a JsonValue.
		/// </summary>
		/// <param name="b">A boolean.</param>
		/// <returns>A JsonValue that represents the boolean.</returns>
		/// <remarks>
		/// This is useful when creating an initialized JsonObject or JsonArray.
		/// </remarks>
		/// <example><code>
		/// JsonObject obj = new JsonObject{
		///		{"stringData", "string"},
		///		{"numberData", 10.6},
		///		{"boolData", true},
		///		{"arrayData", new JsonArray{false, "Array String", JsonValue.Null, 8e-4}},
		///		{"objectData", new JsonObject{
		///			{"stringData2", "another string"},
		///			{"moreBoolData", false}}}};
		/// </code></example>
		public static implicit operator JsonValue(bool b)
		{
			return new JsonValue(b);
		}
		/// <summary>
		/// Implicitly converts a string into a JsonValue.
		/// </summary>
		/// <param name="s">A string.</param>
		/// <returns>A JsonValue that represents the string.</returns>
		/// <remarks>
		/// This is useful when creating an initialized JsonObject or JsonArray.
		/// </remarks>
		/// <example><code>
		/// JsonObject obj = new JsonObject{
		///		{"stringData", "string"},
		///		{"numberData", 10.6},
		///		{"boolData", true},
		///		{"arrayData", new JsonArray{false, "Array String", JsonValue.Null, 8e-4}},
		///		{"objectData", new JsonObject{
		///			{"stringData2", "another string"},
		///			{"moreBoolData", false}}}};
		/// </code></example>
		public static implicit operator JsonValue(string s)
		{
			return new JsonValue(s);
		}
		/// <summary>
		/// Implicitly converts a double into a JsonValue.
		/// </summary>
		/// <param name="n">A double.</param>
		/// <returns>A JsonValue that represents the double.</returns>
		/// <remarks>
		/// This is useful when creating an initialized JsonObject or JsonArray.
		/// </remarks>
		/// <example><code>
		/// JsonObject obj = new JsonObject{
		///		{"stringData", "string"},
		///		{"numberData", 10.6},
		///		{"boolData", true},
		///		{"arrayData", new JsonArray{false, "Array String", JsonValue.Null, 8e-4}},
		///		{"objectData", new JsonObject{
		///			{"stringData2", "another string"},
		///			{"moreBoolData", false}}}};
		/// </code></example>
		public static implicit operator JsonValue(double n)
		{
			return new JsonValue(n);
		}
		/// <summary>
		/// Implicitly converts a JSON object into a JsonValue.
		/// </summary>
		/// <param name="o">A Json object.</param>
		/// <returns>A JsonValue that represents the Json object.</returns>
		/// <remarks>
		/// This is useful when creating an initialized JsonObject or JsonArray.
		/// </remarks>
		/// <example><code>
		/// JsonObject obj = new JsonObject{
		///		{"stringData", "string"},
		///		{"numberData", 10.6},
		///		{"boolData", true},
		///		{"arrayData", new JsonArray{false, "Array String", JsonValue.Null, 8e-4}},
		///		{"objectData", new JsonObject{
		///			{"stringData2", "another string"},
		///			{"moreBoolData", false}}}};
		/// </code></example>
		public static implicit operator JsonValue(JsonObject o)
		{
			return new JsonValue(o);
		}
		/// <summary>
		/// Implicitly converts a JSON array into a JsonValue.
		/// </summary>
		/// <param name="a">A Json array.</param>
		/// <returns>A JsonValue that represents the Json array.</returns>
		/// <remarks>
		/// This is useful when creating an initialized JsonObject or JsonArray.
		/// </remarks>
		/// <example><code>
		/// JsonObject obj = new JsonObject{
		///		{"stringData", "string"},
		///		{"numberData", 10.6},
		///		{"boolData", true},
		///		{"arrayData", new JsonArray{false, "Array String", JsonValue.Null, 8e-4}},
		///		{"objectData", new JsonObject{
		///			{"stringData2", "another string"},
		///			{"moreBoolData", false}}}};
		/// </code></example>
		public static implicit operator JsonValue(JsonArray a)
		{
			return new JsonValue(a);
		}
		///<summary>
		///</summary>
		///<param name="a"></param>
		///<param name="b"></param>
		///<returns></returns>
		public static bool operator ==(JsonValue a, JsonValue b)
		{
			return ReferenceEquals(a,b) || ((a != null) && (a.Equals(b)));
		}

		///<summary>
		///</summary>
		///<param name="a"></param>
		///<param name="b"></param>
		///<returns></returns>
		public static bool operator !=(JsonValue a, JsonValue b)
		{
			return !Equals(a, b);
		}

		internal static JsonValue Parse(string source, ref int index)
		{
			string temp;
			int length;
			switch (source[index-1])
			{
				case '"':										// string
					temp = source.Substring(index);
					if (temp.Length < 2)
						throw new JsonValueParseException(JsonValueType.String, index);
					length = 0;
					var found = false;
					while (!found && length < temp.Length)
					{
						if (temp[length] == '\\')
							if (!EscapeChars.Contains(temp[length + 1].ToString()))
								throw new JsonStringInvalidEscapeSequenceException(temp.Substring(length, 2), index + length);
							else
								if (temp[length + 1] == 'u')
									length += 4;
								else
									length++;
						else found = (temp[length] == '"');
						length++;
					}
					if (!found)
						throw new JsonValueParseException(JsonValueType.String, index);
					if (length == 0)
					{
						index += 2;
						return new JsonValue("");
					}
					index += length;
					return new JsonValue(EvaluateEscapeSequences(temp.Substring(0, length-1)));
				case '{':										// object
					index--;
					return new JsonValue(new JsonObject(source, ref index));
				case '[':										// array
					index--;
					return new JsonValue(new JsonArray(source, ref index));
				default:										// bool, number, null
					temp = source.Substring(index-1);
					length = temp.IndexOfAny(new[] { ',', ']', '}' });
					if (length > 0) temp = temp.Substring(0, length);
					index += temp.Length - 1;
					switch (temp.ToLower())
					{
						case "true":
							return new JsonValue(true);
						case "false":
							return new JsonValue(false);
						case "null":
							return Null;
						default:
							double d;
							if (!double.TryParse(temp, out d))
								throw new JsonValueParseException(JsonValueType.Number, index);
							return new JsonValue(d);
					}
			}
		}

		internal static string EvaluateEscapeSequences(string s)
		{
			var i = 0;
			while (i < s.Length)
			{
				if (s[i] == '\\')
					switch (s[i + 1])
					{
						case '"':
						case '/':
						case '\\':
							s = s.Remove(i, 1);
							break;
						case 'b':
							s = s.Substring(0, i) + '\b' + s.Substring(i + 2);
							break;
						case 'f':
							s = s.Substring(0, i) + '\f' + s.Substring(i + 2);
							break;
						case 'n':
							s = s.Substring(0, i) + '\n' + s.Substring(i + 2);
							break;
						case 'r':
							s = s.Substring(0, i) + '\r' + s.Substring(i + 2);
							break;
						case 't':
							s = s.Substring(0, i) + '\t' + s.Substring(i + 2);
							break;
						case 'u':
							var hex = int.Parse(s.Substring(i + 2, 4), NumberStyles.HexNumber);
							s = s.Substring(0, i) + (char)hex + s.Substring(i + 6);
							break;
					}
				i++;
			}
			return s;
		}

		internal static string InsertEscapeSequences(string s)
		{
			var i = 0;
			while (i < s.Length)
			{
				switch (s[i])
				{
					case '"':
					case '/':
					case '\\':
						s = s.Insert(i, "\\");
						i++;
						break;
					case '\b':
						s = s.Substring(0, i) + "\\b" + s.Substring(i + 1);
						i++;
						break;
					case '\f':
						s = s.Substring(0, i) + "\\f" + s.Substring(i + 1);
						i++;
						break;
					case '\n':
						s = s.Substring(0, i) + "\\n" + s.Substring(i + 1);
						i++;
						break;
					case '\r':
						s = s.Substring(0, i) + "\\r" + s.Substring(i + 1);
						i++;
						break;
					case '\t':
						s = s.Substring(0, i) + "\\t" + s.Substring(i + 1);
						i++;
						break;
					default:
						if (!TypeableChars.Contains(s[i].ToString()))
						{
							var hex = Convert.ToInt16(s[i]).ToString("X4");
							s = s.Substring(0, i) + "\\u" + hex + s.Substring(i + 1);
							i += 5;
						}
						break;
				}
				i++;
			}
			return s;
		}

		private static bool IsWhiteSpace(char c)
		{
			return (c == 10) || (c == 13) || (c == 32) || (c == 9);
		}
		private static string StripExternalSpaces(string s)
		{
			var inString = false;
			var ret = "";
			for (var i = 0; i < s.Length; i++)
			{
				if (s[i] == '"') inString = !inString;
				if (inString || !IsWhiteSpace(s[i]))
					ret += s[i];
			}
			return ret;
		}
	}
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.