Json.NET
Code Coverage Statistics for Source File

Newtonsoft.Json\JsonConvert.cs

Symbol Coverage: 91.89% (204 of 222)

Branch Coverage: 90.09% (100 of 111)

Cyclomatic Complexity Avg: 1.93 Max:20

Code Lines: 226


L V Source
1
#region License
2
// Copyright (c) 2007 James Newton-King
3
//
4
// Permission is hereby granted, free of charge, to any person
5
// obtaining a copy of this software and associated documentation
6
// files (the "Software"), to deal in the Software without
7
// restriction, including without limitation the rights to use,
8
// copy, modify, merge, publish, distribute, sublicense, and/or sell
9
// copies of the Software, and to permit persons to whom the
10
// Software is furnished to do so, subject to the following
11
// conditions:
12
//
13
// The above copyright notice and this permission notice shall be
14
// included in all copies or substantial portions of the Software.
15
//
16
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23
// OTHER DEALINGS IN THE SOFTWARE.
24
#endregion
25

  
26
using System;
27
using System.IO;
28
using System.Globalization;
29
using Newtonsoft.Json.Utilities;
30
using System.Xml;
31
using Newtonsoft.Json.Converters;
32
using System.Text;
33
#if !NET20 && !SILVERLIGHT
34
using System.Xml.Linq;
35
#endif
36

  
37
namespace Newtonsoft.Json
38
{
39
  /// <summary>
40
  /// Provides methods for converting between common language runtime types and JSON types.
41
  /// </summary>
42
  public static class JsonConvert
43
  {
44
    /// <summary>
45
    /// Represents JavaScript's boolean value true as a string. This field is read-only.
46
    /// </summary>
47
 1
    public static readonly string True = "true";
48

  
49
    /// <summary>
50
    /// Represents JavaScript's boolean value false as a string. This field is read-only.
51
    /// </summary>
52
 1
    public static readonly string False = "false";
53

  
54
    /// <summary>
55
    /// Represents JavaScript's null as a string. This field is read-only.
56
    /// </summary>
57
 1
    public static readonly string Null = "null";
58

  
59
    /// <summary>
60
    /// Represents JavaScript's undefined as a string. This field is read-only.
61
    /// </summary>
62
 1
    public static readonly string Undefined = "undefined";
63

  
64
    /// <summary>
65
    /// Represents JavaScript's positive infinity as a string. This field is read-only.
66
    /// </summary>
67
 1
    public static readonly string PositiveInfinity = "Infinity";
68

  
69
    /// <summary>
70
    /// Represents JavaScript's negative infinity as a string. This field is read-only.
71
    /// </summary>
72
 1
    public static readonly string NegativeInfinity = "-Infinity";
73

  
74
    /// <summary>
75
    /// Represents JavaScript's NaN as a string. This field is read-only.
76
    /// </summary>
77
 1
    public static readonly string NaN = "NaN";
78

  
79
 1
    internal static readonly long InitialJavaScriptDateTicks = 621355968000000000;
80

  
81
    /// <summary>
82
    /// Converts the <see cref="DateTime"/> to its JSON string representation.
83
    /// </summary>
84
    /// <param name="value">The value to convert.</param>
85
    /// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
86
    public static string ToString(DateTime value)
87
    {
88
 1
      using (StringWriter writer = StringUtils.CreateStringWriter(64))
89
      {
90
 1
        WriteDateTimeString(writer, value, GetUtcOffset(value), value.Kind);
91
 1
        return writer.ToString();
92
      }
93
 1
    }
94

  
95
#if !PocketPC && !NET20
96
    /// <summary>
97
    /// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
98
    /// </summary>
99
    /// <param name="value">The value to convert.</param>
100
    /// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
101
    public static string ToString(DateTimeOffset value)
102
    {
103
 7
      using (StringWriter writer = StringUtils.CreateStringWriter(64))
104
      {
105
 7
        WriteDateTimeString(writer, value.UtcDateTime, value.Offset, DateTimeKind.Local);
106
 7
        return writer.ToString();
107
      }
108
 7
    }
109
#endif
110

  
111
    private static TimeSpan GetUtcOffset(DateTime dateTime)
112
    {
113
#if SILVERLIGHT
114
      return TimeZoneInfo.Local.GetUtcOffset(dateTime);
115
#else
116
 20874
      return TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
117
#endif
118
 20874
    }
119

  
120
    internal static void WriteDateTimeString(TextWriter writer, DateTime value)
121
    {
122
 20873
      WriteDateTimeString(writer, value, GetUtcOffset(value), value.Kind);
123
 20873
    }
124

  
125
    internal static void WriteDateTimeString(TextWriter writer, DateTime value, TimeSpan offset, DateTimeKind kind)
126
    {
127
 20881
      long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value, offset);
128

  
129
 20881
      writer.Write(@"""\/Date(");
130
 20881
      writer.Write(javaScriptTicks);
131
      
132
 20881
      switch (kind)
133
      {
134
        case DateTimeKind.Local:
135
        case DateTimeKind.Unspecified:
136
 20826
          writer.Write((offset.Ticks >= 0L) ? "+" : "-");
137

  
138
 20826
          int absHours = Math.Abs(offset.Hours);
139
 20826
          if (absHours < 10)
140
 20825
            writer.Write(0);
141
 20826
          writer.Write(absHours);
142
 20826
          int absMinutes = Math.Abs(offset.Minutes);
143
 20826
          if (absMinutes < 10)
144
 20825
            writer.Write(0);
145
 20826
          writer.Write(absMinutes);
146
 20826
          break;
147
      }
148

  
149
 20881
      writer.Write(@")\/""");
150
 20881
    }
151

  
152
    private static long ToUniversalTicks(DateTime dateTime)
153
    {
154
 20825
      if (dateTime.Kind == DateTimeKind.Utc)
155
 20825
        return dateTime.Ticks;
156

  
157
 0
      return ToUniversalTicks(dateTime, GetUtcOffset(dateTime));
158
 20825
    }
159

  
160
    private static long ToUniversalTicks(DateTime dateTime, TimeSpan offset)
161
    {
162
 20882
      if (dateTime.Kind == DateTimeKind.Utc)
163
 63
        return dateTime.Ticks;
164

  
165
 20819
      long ticks = dateTime.Ticks - offset.Ticks;
166
 20819
      if (ticks > 3155378975999999999L)
167
 0
        return 3155378975999999999L;
168

  
169
 20819
      if (ticks < 0L)
170
 0
        return 0L;
171

  
172
 20819
      return ticks;
173
 20882
    }
174

  
175
    internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, TimeSpan offset)
176
    {
177
 20882
      long universialTicks = ToUniversalTicks(dateTime, offset);
178

  
179
 20882
      return UniversialTicksToJavaScriptTicks(universialTicks);
180
 20882
    }
181

  
182
    internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime)
183
    {
184
 20825
      long universialTicks = ToUniversalTicks(dateTime);
185

  
186
 20825
      return UniversialTicksToJavaScriptTicks(universialTicks);
187
 20825
    }
188

  
189
    private static long UniversialTicksToJavaScriptTicks(long universialTicks)
190
    {
191
 41707
      long javaScriptTicks = (universialTicks - InitialJavaScriptDateTicks) / 10000;
192

  
193
 41707
      return javaScriptTicks;
194
 41707
    }
195

  
196
    internal static DateTime ConvertJavaScriptTicksToDateTime(long javaScriptTicks)
197
    {
198
 40076
      DateTime dateTime = new DateTime((javaScriptTicks * 10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc);
199

  
200
 40076
      return dateTime;
201
 40076
    }
202

  
203
    /// <summary>
204
    /// Converts the <see cref="Boolean"/> to its JSON string representation.
205
    /// </summary>
206
    /// <param name="value">The value to convert.</param>
207
    /// <returns>A JSON string representation of the <see cref="Boolean"/>.</returns>
208
    public static string ToString(bool value)
209
    {
210
 38
      return (value) ? True : False;
211
 38
    }
212

  
213
    /// <summary>
214
    /// Converts the <see cref="Char"/> to its JSON string representation.
215
    /// </summary>
216
    /// <param name="value">The value to convert.</param>
217
    /// <returns>A JSON string representation of the <see cref="Char"/>.</returns>
218
    public static string ToString(char value)
219
    {
220
 10
      return ToString(char.ToString(value));
221
 10
    }
222

  
223
    /// <summary>
224
    /// Converts the <see cref="Enum"/> to its JSON string representation.
225
    /// </summary>
226
    /// <param name="value">The value to convert.</param>
227
    /// <returns>A JSON string representation of the <see cref="Enum"/>.</returns>
228
    public static string ToString(Enum value)
229
    {
230
 1
      return value.ToString("D");
231
 1
    }
232

  
233
    /// <summary>
234
    /// Converts the <see cref="Int32"/> to its JSON string representation.
235
    /// </summary>
236
    /// <param name="value">The value to convert.</param>
237
    /// <returns>A JSON string representation of the <see cref="Int32"/>.</returns>
238
    public static string ToString(int value)
239
    {
240
 15779
      return value.ToString(null, CultureInfo.InvariantCulture);
241
 15779
    }
242

  
243
    /// <summary>
244
    /// Converts the <see cref="Int16"/> to its JSON string representation.
245
    /// </summary>
246
    /// <param name="value">The value to convert.</param>
247
    /// <returns>A JSON string representation of the <see cref="Int16"/>.</returns>
248
    public static string ToString(short value)
249
    {
250
 6
      return value.ToString(null, CultureInfo.InvariantCulture);
251
 6
    }
252

  
253
    /// <summary>
254
    /// Converts the <see cref="UInt16"/> to its JSON string representation.
255
    /// </summary>
256
    /// <param name="value">The value to convert.</param>
257
    /// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns>
258
    public static string ToString(ushort value)
259
    {
260
 4
      return value.ToString(null, CultureInfo.InvariantCulture);
261
 4
    }
262

  
263
    /// <summary>
264
    /// Converts the <see cref="UInt32"/> to its JSON string representation.
265
    /// </summary>
266
    /// <param name="value">The value to convert.</param>
267
    /// <returns>A JSON string representation of the <see cref="UInt32"/>.</returns>
268
    public static string ToString(uint value)
269
    {
270
 4
      return value.ToString(null, CultureInfo.InvariantCulture);
271
 4
    }
272

  
273
    /// <summary>
274
    /// Converts the <see cref="Int64"/>  to its JSON string representation.
275
    /// </summary>
276
    /// <param name="value">The value to convert.</param>
277
    /// <returns>A JSON string representation of the <see cref="Int64"/>.</returns>
278
    public static string ToString(long value)
279
    {
280
 61
      return value.ToString(null, CultureInfo.InvariantCulture);
281
 61
    }
282

  
283
    /// <summary>
284
    /// Converts the <see cref="UInt64"/> to its JSON string representation.
285
    /// </summary>
286
    /// <param name="value">The value to convert.</param>
287
    /// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns>
288
    public static string ToString(ulong value)
289
    {
290
 4
      return value.ToString(null, CultureInfo.InvariantCulture);
291
 4
    }
292

  
293
    /// <summary>
294
    /// Converts the <see cref="Single"/> to its JSON string representation.
295
    /// </summary>
296
    /// <param name="value">The value to convert.</param>
297
    /// <returns>A JSON string representation of the <see cref="Single"/>.</returns>
298
    public static string ToString(float value)
299
    {
300
 12
      return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
301
 12
    }
302

  
303
    /// <summary>
304
    /// Converts the <see cref="Double"/> to its JSON string representation.
305
    /// </summary>
306
    /// <param name="value">The value to convert.</param>
307
    /// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
308
    public static string ToString(double value)
309
    {
310
 53
      return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
311
 53
    }
312

  
313
    private static string EnsureDecimalPlace(double value, string text)
314
    {
315
 65
      if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1)
316
 53
        return text;
317

  
318
 12
      return text + ".0";
319
 65
    }
320

  
321
    private static string EnsureDecimalPlace(string text)
322
    {
323
 5260
      if (text.IndexOf('.') != -1)
324
 5237
        return text;
325

  
326
 23
      return text + ".0";
327
 5260
    }
328

  
329
    /// <summary>
330
    /// Converts the <see cref="Byte"/> to its JSON string representation.
331
    /// </summary>
332
    /// <param name="value">The value to convert.</param>
333
    /// <returns>A JSON string representation of the <see cref="Byte"/>.</returns>
334
    public static string ToString(byte value)
335
    {
336
 5
      return value.ToString(null, CultureInfo.InvariantCulture);
337
 5
    }
338

  
339
    /// <summary>
340
    /// Converts the <see cref="SByte"/> to its JSON string representation.
341
    /// </summary>
342
    /// <param name="value">The value to convert.</param>
343
    /// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
344
    public static string ToString(sbyte value)
345
    {
346
 4
      return value.ToString(null, CultureInfo.InvariantCulture);
347
 4
    }
348

  
349
    /// <summary>
350
    /// Converts the <see cref="Decimal"/> to its JSON string representation.
351
    /// </summary>
352
    /// <param name="value">The value to convert.</param>
353
    /// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
354
    public static string ToString(decimal value)
355
    {
356
 5260
      return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
357
 5260
    }
358

  
359
    /// <summary>
360
    /// Converts the <see cref="Guid"/> to its JSON string representation.
361
    /// </summary>
362
    /// <param name="value">The value to convert.</param>
363
    /// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
364
    public static string ToString(Guid value)
365
    {
366
 1
      return '"' + value.ToString("D", CultureInfo.InvariantCulture) + '"';
367
 1
    }
368

  
369
    /// <summary>
370
    /// Converts the <see cref="String"/> to its JSON string representation.
371
    /// </summary>
372
    /// <param name="value">The value to convert.</param>
373
    /// <returns>A JSON string representation of the <see cref="String"/>.</returns>
374
    public static string ToString(string value)
375
    {
376
 12
      return ToString(value, '"');
377
 12
    }
378

  
379
    /// <summary>
380
    /// Converts the <see cref="String"/> to its JSON string representation.
381
    /// </summary>
382
    /// <param name="value">The value to convert.</param>
383
    /// <param name="delimter">The string delimiter character.</param>
384
    /// <returns>A JSON string representation of the <see cref="String"/>.</returns>
385
    public static string ToString(string value, char delimter)
386
    {
387
 12
      return JavaScriptUtils.ToEscapedJavaScriptString(value, delimter, true);
388
 12
    }
389

  
390
    /// <summary>
391
    /// Converts the <see cref="Object"/> to its JSON string representation.
392
    /// </summary>
393
    /// <param name="value">The value to convert.</param>
394
    /// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
395
    public static string ToString(object value)
396
    {
397
 19
      if (value == null)
398
 1
        return Null;
399

  
400
 18
      IConvertible convertible = value as IConvertible;
401

  
402
 18
      if (convertible != null)
403
      {
404
 16
        switch (convertible.GetTypeCode())
405
        {
406
          case TypeCode.String:
407
 1
            return ToString(convertible.ToString(CultureInfo.InvariantCulture));
408
          case TypeCode.Char:
409
 1
            return ToString(convertible.ToChar(CultureInfo.InvariantCulture));
410
          case TypeCode.Boolean:
411
 1
            return ToString(convertible.ToBoolean(CultureInfo.InvariantCulture));
412
          case TypeCode.SByte:
413
 1
            return ToString(convertible.ToSByte(CultureInfo.InvariantCulture));
414
          case TypeCode.Int16:
415
 1
            return ToString(convertible.ToInt16(CultureInfo.InvariantCulture));
416
          case TypeCode.UInt16:
417
 1
            return ToString(convertible.ToUInt16(CultureInfo.InvariantCulture));
418
          case TypeCode.Int32:
419
 1
            return ToString(convertible.ToInt32(CultureInfo.InvariantCulture));
420
          case TypeCode.Byte:
421
 1
            return ToString(convertible.ToByte(CultureInfo.InvariantCulture));
422
          case TypeCode.UInt32:
423
 1
            return ToString(convertible.ToUInt32(CultureInfo.InvariantCulture));
424
          case TypeCode.Int64:
425
 1
            return ToString(convertible.ToInt64(CultureInfo.InvariantCulture));
426
          case TypeCode.UInt64:
427
 1
            return ToString(convertible.ToUInt64(CultureInfo.InvariantCulture));
428
          case TypeCode.Single:
429
 1
            return ToString(convertible.ToSingle(CultureInfo.InvariantCulture));
430
          case TypeCode.Double:
431
 1
            return ToString(convertible.ToDouble(CultureInfo.InvariantCulture));
432
          case TypeCode.DateTime:
433
 1
            return ToString(convertible.ToDateTime(CultureInfo.InvariantCulture));
434
          case TypeCode.Decimal:
435
 1
            return ToString(convertible.ToDecimal(CultureInfo.InvariantCulture));
436
          case TypeCode.DBNull:
437
 1
            return Null;
438
        }
439
      }
440
#if !PocketPC && !NET20
441
 2
      else if (value is DateTimeOffset)
442
      {
443
 1
        return ToString((DateTimeOffset)value);
444
      }
445
#endif
446

  
447
 1
      throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
448
 18
    }
449

  
450
    private static bool IsJsonPrimitiveTypeCode(TypeCode typeCode)
451
    {
452
 306
      switch (typeCode)
453
      {
454
        case TypeCode.String:
455
        case TypeCode.Char:
456
        case TypeCode.Boolean:
457
        case TypeCode.SByte:
458
        case TypeCode.Int16:
459
        case TypeCode.UInt16:
460
        case TypeCode.Int32:
461
        case TypeCode.Byte:
462
        case TypeCode.UInt32:
463
        case TypeCode.Int64:
464
        case TypeCode.UInt64:
465
        case TypeCode.Single:
466
        case TypeCode.Double:
467
        case TypeCode.DateTime:
468
        case TypeCode.Decimal:
469
        case TypeCode.DBNull:
470
 42
          return true;
471
        default:
472
 264
          return false;
473
      }
474
 306
    }
475

  
476
    internal static bool IsJsonPrimitiveType(Type type)
477
    {
478
 309
      if (ReflectionUtils.IsNullableType(type))
479
 8
        type = Nullable.GetUnderlyingType(type);
480

  
481
#if !PocketPC && !NET20
482
 309
     if (type == typeof(DateTimeOffset))
483
 2
        return true;
484
#endif
485
 307
      if (type == typeof(byte[]))
486
 1
        return true;
487

  
488
 306
      return IsJsonPrimitiveTypeCode(Type.GetTypeCode(type));
489
 309
    }
490

  
491
    internal static bool IsJsonPrimitive(object value)
492
    {
493
 0
      if (value == null)
494
 0
        return true;
495

  
496
 0
      IConvertible convertible = value as IConvertible;
497

  
498
 0
      if (convertible != null)
499
 0
        return IsJsonPrimitiveTypeCode(convertible.GetTypeCode());
500

  
501
#if !PocketPC && !NET20
502
 0
      if (value is DateTimeOffset)
503
 0
        return true;
504
#endif
505

  
506
 0
      if (value is byte[])
507
 0
        return true;
508

  
509
 0
      return false;
510
 0
    }
511

  
512
    /// <summary>
513
    /// Serializes the specified object to a JSON string.
514
    /// </summary>
515
    /// <param name="value">The object to serialize.</param>
516
    /// <returns>A JSON string representation of the object.</returns>
517
    public static string SerializeObject(object value)
518
    {
519
 5059
      return SerializeObject(value, Formatting.None, (JsonSerializerSettings)null);
520
 5056
    }
521

  
522
    /// <summary>
523
    /// Serializes the specified object to a JSON string.
524
    /// </summary>
525
    /// <param name="value">The object to serialize.</param>
526
    /// <param name="formatting">Indicates how the output is formatted.</param>
527
    /// <returns>
528
    /// A JSON string representation of the object.
529
    /// </returns>
530
    public static string SerializeObject(object value, Formatting formatting)
531
    {
532
 472
      return SerializeObject(value, formatting, (JsonSerializerSettings)null);
533
 470
    }
534

  
535
    /// <summary>
536
    /// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
537
    /// </summary>
538
    /// <param name="value">The object to serialize.</param>
539
    /// <param name="converters">A collection converters used while serializing.</param>
540
    /// <returns>A JSON string representation of the object.</returns>
541
    public static string SerializeObject(object value, params JsonConverter[] converters)
542
    {
543
 28
      return SerializeObject(value, Formatting.None, converters);
544
 28
    }
545

  
546
    /// <summary>
547
    /// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
548
    /// </summary>
549
    /// <param name="value">The object to serialize.</param>
550
    /// <param name="formatting">Indicates how the output is formatted.</param>
551
    /// <param name="converters">A collection converters used while serializing.</param>
552
    /// <returns>A JSON string representation of the object.</returns>
553
    public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
554
    {
555
 70
      JsonSerializerSettings settings = (converters != null && converters.Length > 0)
556
 70
        ? new JsonSerializerSettings { Converters = converters }
557
 70
        : null;
558

  
559
 70
      return SerializeObject(value, formatting, settings);
560
 70
    }
561

  
562
    /// <summary>
563
    /// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
564
    /// </summary>
565
    /// <param name="value">The object to serialize.</param>
566
    /// <param name="formatting">Indicates how the output is formatted.</param>
567
    /// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
568
    /// If this is null, default serialization settings will be is used.</param>
569
    /// <returns>
570
    /// A JSON string representation of the object.
571
    /// </returns>
572
    public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
573
    {
574
 5631
      JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
575

  
576
 5631
      StringBuilder sb = new StringBuilder(128);
577
 5631
      StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
578
 5631
      using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
579
      {
580
 5631
        jsonWriter.Formatting = formatting;
581

  
582
 5631
        jsonSerializer.Serialize(jsonWriter, value);
583
      }
584

  
585
 5625
      return sw.ToString();
586
 5625
    }
587

  
588
    /// <summary>
589
    /// Deserializes the specified object to a Json object.
590
    /// </summary>
591
    /// <param name="value">The object to deserialize.</param>
592
    /// <returns>The deserialized object from the Json string.</returns>
593
    public static object DeserializeObject(string value)
594
    {
595
 6
      return DeserializeObject(value, null, (JsonSerializerSettings)null);
596
 6
    }
597

  
598
    /// <summary>
599
    /// Deserializes the specified object to a Json object.
600
    /// </summary>
601
    /// <param name="value">The object to deserialize.</param>
602
    /// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
603
    /// <returns>The deserialized object from the Json string.</returns>
604
    public static object DeserializeObject(string value, Type type)
605
    {
606
 11
      return DeserializeObject(value, type, (JsonSerializerSettings)null);
607
 10
    }
608

  
609
    /// <summary>
610
    /// Deserializes the specified object to a Json object.
611
    /// </summary>
612
    /// <typeparam name="T">The type of the object to deserialize.</typeparam>
613
    /// <param name="value">The object to deserialize.</param>
614
    /// <returns>The deserialized object from the Json string.</returns>
615
    public static T DeserializeObject<T>(string value)
616
    {
617
 115
      return DeserializeObject<T>(value, (JsonSerializerSettings)null);
618
 99
    }
619

  
620
    /// <summary>
621
    /// Deserializes the specified JSON to the given anonymous type.
622
    /// </summary>
623
    /// <typeparam name="T">
624
    /// The anonymous type to deserialize to. This can't be specified
625
    /// traditionally and must be infered from the anonymous type passed
626
    /// as a parameter.
627
    /// </typeparam>
628
    /// <param name="value">The object to deserialize.</param>
629
    /// <param name="anonymousTypeObject">The anonymous type object.</param>
630
    /// <returns>The deserialized anonymous type from the JSON string.</returns>
631
    public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
632
    {
633
 1
      return DeserializeObject<T>(value);
634
 1
    }
635

  
636
    /// <summary>
637
    /// Deserializes the JSON string to the specified type.
638
    /// </summary>
639
    /// <typeparam name="T">The type of the object to deserialize.</typeparam>
640
    /// <param name="value">The object to deserialize.</param>
641
    /// <param name="converters">Converters to use while deserializing.</param>
642
    /// <returns>The deserialized object from the JSON string.</returns>
643
    public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
644
    {
645
 33
      return (T)DeserializeObject(value, typeof(T), converters);
646
 31
    }
647

  
648
    /// <summary>
649
    /// Deserializes the JSON string to the specified type.
650
    /// </summary>
651
    /// <typeparam name="T">The type of the object to deserialize.</typeparam>
652
    /// <param name="value">The object to deserialize.</param>
653
    /// <param name="settings">
654
    /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
655
    /// If this is null, default serialization settings will be is used.
656
    /// </param>
657
    /// <returns>The deserialized object from the JSON string.</returns>
658
    public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
659
    {
660
 135
      return (T)DeserializeObject(value, typeof(T), settings);
661
 116
    }
662

  
663
    /// <summary>
664
    /// Deserializes the JSON string to the specified type.
665
    /// </summary>
666
    /// <param name="value">The object to deserialize.</param>
667
    /// <param name="type">The type of the object to deserialize.</param>
668
    /// <param name="converters">Converters to use while deserializing.</param>
669
    /// <returns>The deserialized object from the JSON string.</returns>
670
    public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
671
    {
672
 43
      JsonSerializerSettings settings = (converters != null && converters.Length > 0)
673
 43
        ? new JsonSerializerSettings { Converters = converters }
674
 43
        : null;
675

  
676
 43
      return DeserializeObject(value, type, settings);
677
 37
    }
678

  
679
    /// <summary>
680
    /// Deserializes the JSON string to the specified type.
681
    /// </summary>
682
    /// <param name="value">The JSON to deserialize.</param>
683
    /// <param name="type">The type of the object to deserialize.</param>
684
    /// <param name="settings">
685
    /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
686
    /// If this is null, default serialization settings will be is used.
687
    /// </param>
688
    /// <returns>The deserialized object from the JSON string.</returns>
689
    public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
690
    {
691
 201
      StringReader sr = new StringReader(value);
692
 201
      JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
693

  
694
      object deserializedValue;
695

  
696
 201
      using (JsonReader jsonReader = new JsonTextReader(sr))
697
      {
698
 201
        deserializedValue = jsonSerializer.Deserialize(jsonReader, type);
699

  
700
 173
        if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
701
 0
          throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
702
      }
703

  
704
 172
      return deserializedValue;
705
 172
    }
706

  
707
    /// <summary>
708
    /// Populates the object with values from the JSON string.
709
    /// </summary>
710
    /// <param name="value">The JSON to populate values from.</param>
711
    /// <param name="target">The target object to populate values onto.</param>
712
    public static void PopulateObject(string value, object target)
713
    {
714
 4
      PopulateObject(value, target, null);
715
 1
    }
716

  
717

  
718
    /// <summary>
719
    /// Populates the object with values from the JSON string.
720
    /// </summary>
721
    /// <param name="value">The JSON to populate values from.</param>
722
    /// <param name="target">The target object to populate values onto.</param>
723
    /// <param name="settings">
724
    /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
725
    /// If this is null, default serialization settings will be is used.
726
    /// </param>
727
    public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
728
    {
729
 7
      StringReader sr = new StringReader(value);
730
 7
      JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
731

  
732
 7
      using (JsonReader jsonReader = new JsonTextReader(sr))
733
      {
734
 7
        jsonSerializer.Populate(jsonReader, target);
735

  
736
 4
        if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
737
 0
          throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
738
      }
739
 4
    }
740

  
741
#if !NET20 && !SILVERLIGHT
742
    /// <summary>
743
    /// Serializes the <see cref="XNode"/> to a JSON string.
744
    /// </summary>
745
    /// <param name="node">The node to convert to JSON.</param>
746
    /// <returns>A JSON string of the XNode.</returns>
747
    public static string SerializeXNode(XObject node)
748
    {
749
 1
      return SerializeXNode(node, Formatting.None);
750
 1
    }
751

  
752
    /// <summary>
753
    /// Serializes the <see cref="XNode"/> to a JSON string.
754
    /// </summary>
755
    /// <param name="node">The node to convert to JSON.</param>
756
    /// <param name="formatting">Indicates how the output is formatted.</param>
757
    /// <returns>A JSON string of the XNode.</returns>
758
    public static string SerializeXNode(XObject node, Formatting formatting)
759
    {
760
 13
      XmlNodeConverter converter = new XmlNodeConverter();
761

  
762
 13
      return SerializeObject(node, formatting, converter);
763
 13
    }
764

  
765
    /// <summary>
766
    /// Deserializes the <see cref="XNode"/> from a JSON string.
767
    /// </summary>
768
    /// <param name="value">The JSON string.</param>
769
    /// <returns>The deserialized XNode</returns>
770
    public static XDocument DeserializeXNode(string value)
771
    {
772
 1
      return DeserializeXNode(value, null);
773
 0
    }
774

  
775
    /// <summary>
776
    /// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment.
777
    /// </summary>
778
    /// <param name="value">The JSON string.</param>
779
    /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
780
    /// <returns>The deserialized XNode</returns>
781
    public static XDocument DeserializeXNode(string value, string deserializeRootElementName)
782
    {
783
 4
      XmlNodeConverter converter = new XmlNodeConverter();
784
 4
      converter.DeserializeRootElementName = deserializeRootElementName;
785

  
786
 4
      return (XDocument)DeserializeObject(value, typeof(XDocument), converter);
787
 3
    }
788
#endif
789

  
790
#if !SILVERLIGHT
791
    /// <summary>
792
    /// Serializes the XML node to a JSON string.
793
    /// </summary>
794
    /// <param name="node">The node to serialize.</param>
795
    /// <returns>A JSON string of the XmlNode.</returns>
796
    public static string SerializeXmlNode(XmlNode node)
797
    {
798
 4
      return SerializeXmlNode(node, Formatting.None);
799
 4
    }
800

  
801
    /// <summary>
802
    /// Serializes the XML node to a JSON string.
803
    /// </summary>
804
    /// <param name="node">The node to serialize.</param>
805
    /// <param name="formatting">Indicates how the output is formatted.</param>
806
    /// <returns>A JSON string of the XmlNode.</returns>
807
    public static string SerializeXmlNode(XmlNode node, Formatting formatting)
808
    {
809
 17
      XmlNodeConverter converter = new XmlNodeConverter();
810

  
811
 17
      return SerializeObject(node, formatting, converter);
812
 17
    }
813

  
814
    /// <summary>
815
    /// Deserializes the XmlNode from a JSON string.
816
    /// </summary>
817
    /// <param name="value">The JSON string.</param>
818
    /// <returns>The deserialized XmlNode</returns>
819
    public static XmlDocument DeserializeXmlNode(string value)
820
    {
821
 3
      return DeserializeXmlNode(value, null);
822
 0
    }
823

  
824
    /// <summary>
825
    /// Deserializes the XmlNode from a JSON string nested in a root elment.
826
    /// </summary>
827
    /// <param name="value">The JSON string.</param>
828
    /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
829
    /// <returns>The deserialized XmlNode</returns>
830
    public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName)
831
    {
832
 6
      XmlNodeConverter converter = new XmlNodeConverter();
833
 6
      converter.DeserializeRootElementName = deserializeRootElementName;
834

  
835
 6
      return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter);
836
 3
    }
837
#endif
838
  }
839
}