~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

« back to all changes in this revision

Viewing changes to external/Newtonsoft.Json/Src/Newtonsoft.Json/JsonConvert.cs

  • Committer: Package Import Robot
  • Author(s): Jo Shields
  • Date: 2013-05-12 09:46:03 UTC
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20130512094603-mad323bzcxvmcam0
Tags: upstream-4.0.5+dfsg
ImportĀ upstreamĀ versionĀ 4.0.5+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
 
30
using System.Threading.Tasks;
 
31
#endif
 
32
using Newtonsoft.Json.Utilities;
 
33
using System.Xml;
 
34
using Newtonsoft.Json.Converters;
 
35
using System.Text;
 
36
#if !NET20 && (!SILVERLIGHT || WINDOWS_PHONE) && !PORTABLE
 
37
using System.Xml.Linq;
 
38
#endif
 
39
#if NETFX_CORE
 
40
using IConvertible = Newtonsoft.Json.Utilities.Convertible;
 
41
#endif
 
42
 
 
43
namespace Newtonsoft.Json
 
44
{
 
45
  /// <summary>
 
46
  /// Provides methods for converting between common language runtime types and JSON types.
 
47
  /// </summary>
 
48
  /// <example>
 
49
  ///   <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="SerializeObject" title="Serializing and Deserializing JSON with JsonConvert" />
 
50
  /// </example>
 
51
  public static class JsonConvert
 
52
  {
 
53
    /// <summary>
 
54
    /// Represents JavaScript's boolean value true as a string. This field is read-only.
 
55
    /// </summary>
 
56
    public static readonly string True = "true";
 
57
 
 
58
    /// <summary>
 
59
    /// Represents JavaScript's boolean value false as a string. This field is read-only.
 
60
    /// </summary>
 
61
    public static readonly string False = "false";
 
62
 
 
63
    /// <summary>
 
64
    /// Represents JavaScript's null as a string. This field is read-only.
 
65
    /// </summary>
 
66
    public static readonly string Null = "null";
 
67
 
 
68
    /// <summary>
 
69
    /// Represents JavaScript's undefined as a string. This field is read-only.
 
70
    /// </summary>
 
71
    public static readonly string Undefined = "undefined";
 
72
 
 
73
    /// <summary>
 
74
    /// Represents JavaScript's positive infinity as a string. This field is read-only.
 
75
    /// </summary>
 
76
    public static readonly string PositiveInfinity = "Infinity";
 
77
 
 
78
    /// <summary>
 
79
    /// Represents JavaScript's negative infinity as a string. This field is read-only.
 
80
    /// </summary>
 
81
    public static readonly string NegativeInfinity = "-Infinity";
 
82
 
 
83
    /// <summary>
 
84
    /// Represents JavaScript's NaN as a string. This field is read-only.
 
85
    /// </summary>
 
86
    public static readonly string NaN = "NaN";
 
87
 
 
88
    internal static readonly long InitialJavaScriptDateTicks = 621355968000000000;
 
89
 
 
90
    /// <summary>
 
91
    /// Converts the <see cref="DateTime"/> to its JSON string representation.
 
92
    /// </summary>
 
93
    /// <param name="value">The value to convert.</param>
 
94
    /// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
 
95
    public static string ToString(DateTime value)
 
96
    {
 
97
      return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
 
98
    }
 
99
 
 
100
    /// <summary>
 
101
    /// Converts the <see cref="DateTime"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
 
102
    /// </summary>
 
103
    /// <param name="value">The value to convert.</param>
 
104
    /// <param name="format">The format the date will be converted to.</param>
 
105
    /// <param name="timeZoneHandling">The time zone handling when the date is converted to a string.</param>
 
106
    /// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
 
107
    public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
 
108
    {
 
109
      DateTime updatedDateTime = EnsureDateTime(value, timeZoneHandling);
 
110
 
 
111
      using (StringWriter writer = StringUtils.CreateStringWriter(64))
 
112
      {
 
113
        WriteDateTimeString(writer, updatedDateTime, updatedDateTime.GetUtcOffset(), updatedDateTime.Kind, format, '"');
 
114
        return writer.ToString();
 
115
      }
 
116
    }
 
117
 
 
118
    internal static DateTime EnsureDateTime(DateTime value, DateTimeZoneHandling timeZone)
 
119
    {
 
120
      switch (timeZone)
 
121
      {
 
122
        case DateTimeZoneHandling.Local:
 
123
          value = SwitchToLocalTime(value);
 
124
          break;
 
125
        case DateTimeZoneHandling.Utc:
 
126
          value = SwitchToUtcTime(value);
 
127
          break;
 
128
        case DateTimeZoneHandling.Unspecified:
 
129
          value = new DateTime(value.Ticks, DateTimeKind.Unspecified);
 
130
          break;
 
131
        case DateTimeZoneHandling.RoundtripKind:
 
132
          break;
 
133
        default:
 
134
          throw new ArgumentException("Invalid date time handling value.");
 
135
      }
 
136
 
 
137
      return value;
 
138
    }
 
139
 
 
140
#if !PocketPC && !NET20
 
141
    /// <summary>
 
142
    /// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
 
143
    /// </summary>
 
144
    /// <param name="value">The value to convert.</param>
 
145
    /// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
 
146
    public static string ToString(DateTimeOffset value)
 
147
    {
 
148
      return ToString(value, DateFormatHandling.IsoDateFormat);
 
149
    }
 
150
 
 
151
    /// <summary>
 
152
    /// Converts the <see cref="DateTimeOffset"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
 
153
    /// </summary>
 
154
    /// <param name="value">The value to convert.</param>
 
155
    /// <param name="format">The format the date will be converted to.</param>
 
156
    /// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
 
157
    public static string ToString(DateTimeOffset value, DateFormatHandling format)
 
158
    {
 
159
      return ToString(value, format, '"');
 
160
    }
 
161
 
 
162
    internal static string ToString(DateTimeOffset value, DateFormatHandling format, char quoteChar)
 
163
    {
 
164
      using (StringWriter writer = StringUtils.CreateStringWriter(64))
 
165
      {
 
166
        WriteDateTimeString(writer, (format == DateFormatHandling.IsoDateFormat) ? value.DateTime : value.UtcDateTime, value.Offset, DateTimeKind.Local, format, quoteChar);
 
167
        return writer.ToString();
 
168
      }
 
169
    }
 
170
#endif
 
171
 
 
172
    internal static void WriteDateTimeString(TextWriter writer, DateTime value, DateFormatHandling format, char quoteChar)
 
173
    {
 
174
      WriteDateTimeString(writer, value, value.GetUtcOffset(), value.Kind, format, quoteChar);
 
175
    }
 
176
 
 
177
    internal static void WriteDateTimeString(TextWriter writer, DateTime value, TimeSpan offset, DateTimeKind kind, DateFormatHandling format, char quoteChar)
 
178
    {
 
179
      if (format == DateFormatHandling.MicrosoftDateFormat)
 
180
      {
 
181
        long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value, offset);
 
182
 
 
183
        writer.Write(quoteChar);
 
184
        writer.Write(@"\/Date(");
 
185
        writer.Write(javaScriptTicks);
 
186
 
 
187
        switch (kind)
 
188
        {
 
189
          case DateTimeKind.Unspecified:
 
190
            if (value != DateTime.MaxValue && value != DateTime.MinValue)
 
191
              WriteDateTimeOffset(writer, offset, format);
 
192
            break;
 
193
          case DateTimeKind.Local:
 
194
            WriteDateTimeOffset(writer, offset, format);
 
195
            break;
 
196
        }
 
197
 
 
198
        writer.Write(@")\/");
 
199
        writer.Write(quoteChar);
 
200
      }
 
201
      else
 
202
      {
 
203
        writer.Write(quoteChar);
 
204
        writer.Write(value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFF", CultureInfo.InvariantCulture));
 
205
 
 
206
        switch (kind)
 
207
        {
 
208
          case DateTimeKind.Local:
 
209
            WriteDateTimeOffset(writer, offset, format);
 
210
            break;
 
211
          case DateTimeKind.Utc:
 
212
            writer.Write("Z");
 
213
            break;
 
214
        }
 
215
 
 
216
 
 
217
        writer.Write(quoteChar);
 
218
      }
 
219
    }
 
220
 
 
221
    internal static void WriteDateTimeOffset(TextWriter writer, TimeSpan offset, DateFormatHandling format)
 
222
    {
 
223
      writer.Write((offset.Ticks >= 0L) ? "+" : "-");
 
224
 
 
225
      int absHours = Math.Abs(offset.Hours);
 
226
      if (absHours < 10)
 
227
        writer.Write(0);
 
228
      writer.Write(absHours);
 
229
 
 
230
      if (format == DateFormatHandling.IsoDateFormat)
 
231
        writer.Write(':');
 
232
 
 
233
      int absMinutes = Math.Abs(offset.Minutes);
 
234
      if (absMinutes < 10)
 
235
        writer.Write(0);
 
236
      writer.Write(absMinutes);
 
237
    }
 
238
 
 
239
    private static long ToUniversalTicks(DateTime dateTime)
 
240
    {
 
241
      if (dateTime.Kind == DateTimeKind.Utc)
 
242
        return dateTime.Ticks;
 
243
 
 
244
      return ToUniversalTicks(dateTime, dateTime.GetUtcOffset());
 
245
    }
 
246
 
 
247
    private static long ToUniversalTicks(DateTime dateTime, TimeSpan offset)
 
248
    {
 
249
      // special case min and max value
 
250
      // they never have a timezone appended to avoid issues
 
251
      if (dateTime.Kind == DateTimeKind.Utc || dateTime == DateTime.MaxValue || dateTime == DateTime.MinValue)
 
252
        return dateTime.Ticks;
 
253
 
 
254
      long ticks = dateTime.Ticks - offset.Ticks;
 
255
      if (ticks > 3155378975999999999L)
 
256
        return 3155378975999999999L;
 
257
 
 
258
      if (ticks < 0L)
 
259
        return 0L;
 
260
 
 
261
      return ticks;
 
262
    }
 
263
 
 
264
    internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, TimeSpan offset)
 
265
    {
 
266
      long universialTicks = ToUniversalTicks(dateTime, offset);
 
267
 
 
268
      return UniversialTicksToJavaScriptTicks(universialTicks);
 
269
    }
 
270
 
 
271
    internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime)
 
272
    {
 
273
      return ConvertDateTimeToJavaScriptTicks(dateTime, true);
 
274
    }
 
275
 
 
276
    internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, bool convertToUtc)
 
277
    {
 
278
      long ticks = (convertToUtc) ? ToUniversalTicks(dateTime) : dateTime.Ticks;
 
279
 
 
280
      return UniversialTicksToJavaScriptTicks(ticks);
 
281
    }
 
282
 
 
283
    private static long UniversialTicksToJavaScriptTicks(long universialTicks)
 
284
    {
 
285
      long javaScriptTicks = (universialTicks - InitialJavaScriptDateTicks)/10000;
 
286
 
 
287
      return javaScriptTicks;
 
288
    }
 
289
 
 
290
    internal static DateTime ConvertJavaScriptTicksToDateTime(long javaScriptTicks)
 
291
    {
 
292
      DateTime dateTime = new DateTime((javaScriptTicks*10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc);
 
293
 
 
294
      return dateTime;
 
295
    }
 
296
 
 
297
    private static DateTime SwitchToLocalTime(DateTime value)
 
298
    {
 
299
      switch (value.Kind)
 
300
      {
 
301
        case DateTimeKind.Unspecified:
 
302
          return new DateTime(value.Ticks, DateTimeKind.Local);
 
303
 
 
304
        case DateTimeKind.Utc:
 
305
          return value.ToLocalTime();
 
306
 
 
307
        case DateTimeKind.Local:
 
308
          return value;
 
309
      }
 
310
      return value;
 
311
    }
 
312
 
 
313
    private static DateTime SwitchToUtcTime(DateTime value)
 
314
    {
 
315
      switch (value.Kind)
 
316
      {
 
317
        case DateTimeKind.Unspecified:
 
318
          return new DateTime(value.Ticks, DateTimeKind.Utc);
 
319
 
 
320
        case DateTimeKind.Utc:
 
321
          return value;
 
322
 
 
323
        case DateTimeKind.Local:
 
324
          return value.ToUniversalTime();
 
325
      }
 
326
      return value;
 
327
    }
 
328
 
 
329
    /// <summary>
 
330
    /// Converts the <see cref="Boolean"/> 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="Boolean"/>.</returns>
 
334
    public static string ToString(bool value)
 
335
    {
 
336
      return (value) ? True : False;
 
337
    }
 
338
 
 
339
    /// <summary>
 
340
    /// Converts the <see cref="Char"/> 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="Char"/>.</returns>
 
344
    public static string ToString(char value)
 
345
    {
 
346
      return ToString(char.ToString(value));
 
347
    }
 
348
 
 
349
    /// <summary>
 
350
    /// Converts the <see cref="Enum"/> 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="Enum"/>.</returns>
 
354
    public static string ToString(Enum value)
 
355
    {
 
356
      return value.ToString("D");
 
357
    }
 
358
 
 
359
    /// <summary>
 
360
    /// Converts the <see cref="Int32"/> 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="Int32"/>.</returns>
 
364
    public static string ToString(int value)
 
365
    {
 
366
      return value.ToString(null, CultureInfo.InvariantCulture);
 
367
    }
 
368
 
 
369
    /// <summary>
 
370
    /// Converts the <see cref="Int16"/> 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="Int16"/>.</returns>
 
374
    public static string ToString(short value)
 
375
    {
 
376
      return value.ToString(null, CultureInfo.InvariantCulture);
 
377
    }
 
378
 
 
379
    /// <summary>
 
380
    /// Converts the <see cref="UInt16"/> to its JSON string representation.
 
381
    /// </summary>
 
382
    /// <param name="value">The value to convert.</param>
 
383
    /// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns>
 
384
    [CLSCompliant(false)]
 
385
    public static string ToString(ushort value)
 
386
    {
 
387
      return value.ToString(null, CultureInfo.InvariantCulture);
 
388
    }
 
389
 
 
390
    /// <summary>
 
391
    /// Converts the <see cref="UInt32"/> 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="UInt32"/>.</returns>
 
395
    [CLSCompliant(false)]
 
396
    public static string ToString(uint value)
 
397
    {
 
398
      return value.ToString(null, CultureInfo.InvariantCulture);
 
399
    }
 
400
 
 
401
    /// <summary>
 
402
    /// Converts the <see cref="Int64"/>  to its JSON string representation.
 
403
    /// </summary>
 
404
    /// <param name="value">The value to convert.</param>
 
405
    /// <returns>A JSON string representation of the <see cref="Int64"/>.</returns>
 
406
    public static string ToString(long value)
 
407
    {
 
408
      return value.ToString(null, CultureInfo.InvariantCulture);
 
409
    }
 
410
 
 
411
    /// <summary>
 
412
    /// Converts the <see cref="UInt64"/> to its JSON string representation.
 
413
    /// </summary>
 
414
    /// <param name="value">The value to convert.</param>
 
415
    /// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns>
 
416
    [CLSCompliant(false)]
 
417
    public static string ToString(ulong value)
 
418
    {
 
419
      return value.ToString(null, CultureInfo.InvariantCulture);
 
420
    }
 
421
 
 
422
    /// <summary>
 
423
    /// Converts the <see cref="Single"/> to its JSON string representation.
 
424
    /// </summary>
 
425
    /// <param name="value">The value to convert.</param>
 
426
    /// <returns>A JSON string representation of the <see cref="Single"/>.</returns>
 
427
    public static string ToString(float value)
 
428
    {
 
429
      return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
 
430
    }
 
431
 
 
432
    /// <summary>
 
433
    /// Converts the <see cref="Double"/> to its JSON string representation.
 
434
    /// </summary>
 
435
    /// <param name="value">The value to convert.</param>
 
436
    /// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
 
437
    public static string ToString(double value)
 
438
    {
 
439
      return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
 
440
    }
 
441
 
 
442
    private static string EnsureDecimalPlace(double value, string text)
 
443
    {
 
444
      if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1)
 
445
        return text;
 
446
 
 
447
      return text + ".0";
 
448
    }
 
449
 
 
450
    private static string EnsureDecimalPlace(string text)
 
451
    {
 
452
      if (text.IndexOf('.') != -1)
 
453
        return text;
 
454
 
 
455
      return text + ".0";
 
456
    }
 
457
 
 
458
    /// <summary>
 
459
    /// Converts the <see cref="Byte"/> to its JSON string representation.
 
460
    /// </summary>
 
461
    /// <param name="value">The value to convert.</param>
 
462
    /// <returns>A JSON string representation of the <see cref="Byte"/>.</returns>
 
463
    public static string ToString(byte value)
 
464
    {
 
465
      return value.ToString(null, CultureInfo.InvariantCulture);
 
466
    }
 
467
 
 
468
    /// <summary>
 
469
    /// Converts the <see cref="SByte"/> to its JSON string representation.
 
470
    /// </summary>
 
471
    /// <param name="value">The value to convert.</param>
 
472
    /// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
 
473
    [CLSCompliant(false)]
 
474
    public static string ToString(sbyte value)
 
475
    {
 
476
      return value.ToString(null, CultureInfo.InvariantCulture);
 
477
    }
 
478
 
 
479
    /// <summary>
 
480
    /// Converts the <see cref="Decimal"/> to its JSON string representation.
 
481
    /// </summary>
 
482
    /// <param name="value">The value to convert.</param>
 
483
    /// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
 
484
    public static string ToString(decimal value)
 
485
    {
 
486
      return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
 
487
    }
 
488
 
 
489
    /// <summary>
 
490
    /// Converts the <see cref="Guid"/> to its JSON string representation.
 
491
    /// </summary>
 
492
    /// <param name="value">The value to convert.</param>
 
493
    /// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
 
494
    public static string ToString(Guid value)
 
495
    {
 
496
      return ToString(value, '"');
 
497
    }
 
498
 
 
499
    internal static string ToString(Guid value, char quoteChar)
 
500
    {
 
501
      string text = null;
 
502
 
 
503
#if !(NETFX_CORE || PORTABLE)
 
504
      text = value.ToString("D", CultureInfo.InvariantCulture);
 
505
#else
 
506
      text = value.ToString("D");
 
507
#endif
 
508
 
 
509
      return quoteChar + text + quoteChar;
 
510
    }
 
511
 
 
512
    /// <summary>
 
513
    /// Converts the <see cref="TimeSpan"/> to its JSON string representation.
 
514
    /// </summary>
 
515
    /// <param name="value">The value to convert.</param>
 
516
    /// <returns>A JSON string representation of the <see cref="TimeSpan"/>.</returns>
 
517
    public static string ToString(TimeSpan value)
 
518
    {
 
519
      return ToString(value, '"');
 
520
    }
 
521
 
 
522
    internal static string ToString(TimeSpan value, char quoteChar)
 
523
    {
 
524
      return ToString(value.ToString(), quoteChar);
 
525
    }
 
526
 
 
527
    /// <summary>
 
528
    /// Converts the <see cref="Uri"/> to its JSON string representation.
 
529
    /// </summary>
 
530
    /// <param name="value">The value to convert.</param>
 
531
    /// <returns>A JSON string representation of the <see cref="Uri"/>.</returns>
 
532
    public static string ToString(Uri value)
 
533
    {
 
534
      if (value == null)
 
535
        return Null;
 
536
 
 
537
      return ToString(value, '"');
 
538
    }
 
539
 
 
540
    internal static string ToString(Uri value, char quoteChar)
 
541
    {
 
542
      return ToString(value.ToString(), quoteChar);
 
543
    }
 
544
 
 
545
    /// <summary>
 
546
    /// Converts the <see cref="String"/> to its JSON string representation.
 
547
    /// </summary>
 
548
    /// <param name="value">The value to convert.</param>
 
549
    /// <returns>A JSON string representation of the <see cref="String"/>.</returns>
 
550
    public static string ToString(string value)
 
551
    {
 
552
      return ToString(value, '"');
 
553
    }
 
554
 
 
555
    /// <summary>
 
556
    /// Converts the <see cref="String"/> to its JSON string representation.
 
557
    /// </summary>
 
558
    /// <param name="value">The value to convert.</param>
 
559
    /// <param name="delimiter">The string delimiter character.</param>
 
560
    /// <returns>A JSON string representation of the <see cref="String"/>.</returns>
 
561
    public static string ToString(string value, char delimiter)
 
562
    {
 
563
      if (delimiter != '"' && delimiter != '\'')
 
564
        throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter");
 
565
 
 
566
      return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true);
 
567
    }
 
568
 
 
569
    /// <summary>
 
570
    /// Converts the <see cref="Object"/> to its JSON string representation.
 
571
    /// </summary>
 
572
    /// <param name="value">The value to convert.</param>
 
573
    /// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
 
574
    public static string ToString(object value)
 
575
    {
 
576
      if (value == null)
 
577
        return Null;
 
578
 
 
579
      IConvertible convertible = ConvertUtils.ToConvertible(value);
 
580
 
 
581
      if (convertible != null)
 
582
      {
 
583
        switch (convertible.GetTypeCode())
 
584
        {
 
585
          case TypeCode.String:
 
586
            return ToString(convertible.ToString(CultureInfo.InvariantCulture));
 
587
          case TypeCode.Char:
 
588
            return ToString(convertible.ToChar(CultureInfo.InvariantCulture));
 
589
          case TypeCode.Boolean:
 
590
            return ToString(convertible.ToBoolean(CultureInfo.InvariantCulture));
 
591
          case TypeCode.SByte:
 
592
            return ToString(convertible.ToSByte(CultureInfo.InvariantCulture));
 
593
          case TypeCode.Int16:
 
594
            return ToString(convertible.ToInt16(CultureInfo.InvariantCulture));
 
595
          case TypeCode.UInt16:
 
596
            return ToString(convertible.ToUInt16(CultureInfo.InvariantCulture));
 
597
          case TypeCode.Int32:
 
598
            return ToString(convertible.ToInt32(CultureInfo.InvariantCulture));
 
599
          case TypeCode.Byte:
 
600
            return ToString(convertible.ToByte(CultureInfo.InvariantCulture));
 
601
          case TypeCode.UInt32:
 
602
            return ToString(convertible.ToUInt32(CultureInfo.InvariantCulture));
 
603
          case TypeCode.Int64:
 
604
            return ToString(convertible.ToInt64(CultureInfo.InvariantCulture));
 
605
          case TypeCode.UInt64:
 
606
            return ToString(convertible.ToUInt64(CultureInfo.InvariantCulture));
 
607
          case TypeCode.Single:
 
608
            return ToString(convertible.ToSingle(CultureInfo.InvariantCulture));
 
609
          case TypeCode.Double:
 
610
            return ToString(convertible.ToDouble(CultureInfo.InvariantCulture));
 
611
          case TypeCode.DateTime:
 
612
            return ToString(convertible.ToDateTime(CultureInfo.InvariantCulture));
 
613
          case TypeCode.Decimal:
 
614
            return ToString(convertible.ToDecimal(CultureInfo.InvariantCulture));
 
615
#if !(NETFX_CORE || PORTABLE)
 
616
          case TypeCode.DBNull:
 
617
            return Null;
 
618
#endif
 
619
        }
 
620
      }
 
621
#if !PocketPC && !NET20
 
622
      else if (value is DateTimeOffset)
 
623
      {
 
624
        return ToString((DateTimeOffset) value);
 
625
      }
 
626
#endif
 
627
      else if (value is Guid)
 
628
      {
 
629
        return ToString((Guid) value);
 
630
      }
 
631
      else if (value is Uri)
 
632
      {
 
633
        return ToString((Uri) value);
 
634
      }
 
635
      else if (value is TimeSpan)
 
636
      {
 
637
        return ToString((TimeSpan) value);
 
638
      }
 
639
 
 
640
      throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
 
641
    }
 
642
 
 
643
    private static bool IsJsonPrimitiveTypeCode(TypeCode typeCode)
 
644
    {
 
645
      switch (typeCode)
 
646
      {
 
647
        case TypeCode.String:
 
648
        case TypeCode.Char:
 
649
        case TypeCode.Boolean:
 
650
        case TypeCode.SByte:
 
651
        case TypeCode.Int16:
 
652
        case TypeCode.UInt16:
 
653
        case TypeCode.Int32:
 
654
        case TypeCode.Byte:
 
655
        case TypeCode.UInt32:
 
656
        case TypeCode.Int64:
 
657
        case TypeCode.UInt64:
 
658
        case TypeCode.Single:
 
659
        case TypeCode.Double:
 
660
        case TypeCode.DateTime:
 
661
        case TypeCode.Decimal:
 
662
#if !(NETFX_CORE || PORTABLE)
 
663
        case TypeCode.DBNull:
 
664
#endif
 
665
          return true;
 
666
        default:
 
667
          return false;
 
668
      }
 
669
    }
 
670
 
 
671
    internal static bool IsJsonPrimitiveType(Type type)
 
672
    {
 
673
      if (ReflectionUtils.IsNullableType(type))
 
674
        type = Nullable.GetUnderlyingType(type);
 
675
 
 
676
#if !PocketPC && !NET20
 
677
      if (type == typeof (DateTimeOffset))
 
678
        return true;
 
679
#endif
 
680
      if (type == typeof (byte[]))
 
681
        return true;
 
682
      if (type == typeof (Uri))
 
683
        return true;
 
684
      if (type == typeof (TimeSpan))
 
685
        return true;
 
686
      if (type == typeof (Guid))
 
687
        return true;
 
688
 
 
689
      return IsJsonPrimitiveTypeCode(ConvertUtils.GetTypeCode(type));
 
690
    }
 
691
 
 
692
    #region Serialize
 
693
    /// <summary>
 
694
    /// Serializes the specified object to a JSON string.
 
695
    /// </summary>
 
696
    /// <param name="value">The object to serialize.</param>
 
697
    /// <returns>A JSON string representation of the object.</returns>
 
698
    public static string SerializeObject(object value)
 
699
    {
 
700
      return SerializeObject(value, Formatting.None, (JsonSerializerSettings) null);
 
701
    }
 
702
 
 
703
    /// <summary>
 
704
    /// Serializes the specified object to a JSON string.
 
705
    /// </summary>
 
706
    /// <param name="value">The object to serialize.</param>
 
707
    /// <param name="formatting">Indicates how the output is formatted.</param>
 
708
    /// <returns>
 
709
    /// A JSON string representation of the object.
 
710
    /// </returns>
 
711
    public static string SerializeObject(object value, Formatting formatting)
 
712
    {
 
713
      return SerializeObject(value, formatting, (JsonSerializerSettings) null);
 
714
    }
 
715
 
 
716
    /// <summary>
 
717
    /// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
 
718
    /// </summary>
 
719
    /// <param name="value">The object to serialize.</param>
 
720
    /// <param name="converters">A collection converters used while serializing.</param>
 
721
    /// <returns>A JSON string representation of the object.</returns>
 
722
    public static string SerializeObject(object value, params JsonConverter[] converters)
 
723
    {
 
724
      return SerializeObject(value, Formatting.None, converters);
 
725
    }
 
726
 
 
727
    /// <summary>
 
728
    /// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
 
729
    /// </summary>
 
730
    /// <param name="value">The object to serialize.</param>
 
731
    /// <param name="formatting">Indicates how the output is formatted.</param>
 
732
    /// <param name="converters">A collection converters used while serializing.</param>
 
733
    /// <returns>A JSON string representation of the object.</returns>
 
734
    public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
 
735
    {
 
736
      JsonSerializerSettings settings = (converters != null && converters.Length > 0)
 
737
                                          ? new JsonSerializerSettings {Converters = converters}
 
738
                                          : null;
 
739
 
 
740
      return SerializeObject(value, formatting, settings);
 
741
    }
 
742
 
 
743
    /// <summary>
 
744
    /// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
 
745
    /// </summary>
 
746
    /// <param name="value">The object to serialize.</param>
 
747
    /// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
 
748
    /// If this is null, default serialization settings will be is used.</param>
 
749
    /// <returns>
 
750
    /// A JSON string representation of the object.
 
751
    /// </returns>
 
752
    public static string SerializeObject(object value, JsonSerializerSettings settings)
 
753
    {
 
754
      return SerializeObject(value, Formatting.None, settings);
 
755
    }
 
756
 
 
757
    /// <summary>
 
758
    /// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
 
759
    /// </summary>
 
760
    /// <param name="value">The object to serialize.</param>
 
761
    /// <param name="formatting">Indicates how the output is formatted.</param>
 
762
    /// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
 
763
    /// If this is null, default serialization settings will be is used.</param>
 
764
    /// <returns>
 
765
    /// A JSON string representation of the object.
 
766
    /// </returns>
 
767
    public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
 
768
    {
 
769
      JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
 
770
 
 
771
      StringBuilder sb = new StringBuilder(256);
 
772
      StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
 
773
      using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
 
774
      {
 
775
        jsonWriter.Formatting = formatting;
 
776
 
 
777
        jsonSerializer.Serialize(jsonWriter, value);
 
778
      }
 
779
 
 
780
      return sw.ToString();
 
781
    }
 
782
 
 
783
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
 
784
    /// <summary>
 
785
    /// Asynchronously serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
 
786
    /// </summary>
 
787
    /// <param name="value">The object to serialize.</param>
 
788
    /// <returns>
 
789
    /// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
 
790
    /// </returns>
 
791
    public static Task<string> SerializeObjectAsync(object value)
 
792
    {
 
793
      return SerializeObjectAsync(value, Formatting.None, null);
 
794
    }
 
795
 
 
796
    /// <summary>
 
797
    /// Asynchronously serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
 
798
    /// </summary>
 
799
    /// <param name="value">The object to serialize.</param>
 
800
    /// <param name="formatting">Indicates how the output is formatted.</param>
 
801
    /// <returns>
 
802
    /// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
 
803
    /// </returns>
 
804
    public static Task<string> SerializeObjectAsync(object value, Formatting formatting)
 
805
    {
 
806
      return SerializeObjectAsync(value, formatting, null);
 
807
    }
 
808
 
 
809
    /// <summary>
 
810
    /// Asynchronously serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
 
811
    /// </summary>
 
812
    /// <param name="value">The object to serialize.</param>
 
813
    /// <param name="formatting">Indicates how the output is formatted.</param>
 
814
    /// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
 
815
    /// If this is null, default serialization settings will be is used.</param>
 
816
    /// <returns>
 
817
    /// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
 
818
    /// </returns>
 
819
    public static Task<string> SerializeObjectAsync(object value, Formatting formatting, JsonSerializerSettings settings)
 
820
    {
 
821
      return Task.Factory.StartNew(() => SerializeObject(value, formatting, settings));
 
822
    }
 
823
#endif
 
824
    #endregion
 
825
 
 
826
    #region Deserialize
 
827
    /// <summary>
 
828
    /// Deserializes the JSON to a .NET object.
 
829
    /// </summary>
 
830
    /// <param name="value">The JSON to deserialize.</param>
 
831
    /// <returns>The deserialized object from the Json string.</returns>
 
832
    public static object DeserializeObject(string value)
 
833
    {
 
834
      return DeserializeObject(value, null, (JsonSerializerSettings) null);
 
835
    }
 
836
 
 
837
    /// <summary>
 
838
    /// Deserializes the JSON to a .NET object.
 
839
    /// </summary>
 
840
    /// <param name="value">The JSON to deserialize.</param>
 
841
    /// <param name="settings">
 
842
    /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
 
843
    /// If this is null, default serialization settings will be is used.
 
844
    /// </param>
 
845
    /// <returns>The deserialized object from the JSON string.</returns>
 
846
    public static object DeserializeObject(string value, JsonSerializerSettings settings)
 
847
    {
 
848
      return DeserializeObject(value, null, settings);
 
849
    }
 
850
 
 
851
    /// <summary>
 
852
    /// Deserializes the JSON to the specified .NET type.
 
853
    /// </summary>
 
854
    /// <param name="value">The JSON to deserialize.</param>
 
855
    /// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
 
856
    /// <returns>The deserialized object from the Json string.</returns>
 
857
    public static object DeserializeObject(string value, Type type)
 
858
    {
 
859
      return DeserializeObject(value, type, (JsonSerializerSettings) null);
 
860
    }
 
861
 
 
862
    /// <summary>
 
863
    /// Deserializes the JSON to the specified .NET type.
 
864
    /// </summary>
 
865
    /// <typeparam name="T">The type of the object to deserialize to.</typeparam>
 
866
    /// <param name="value">The JSON to deserialize.</param>
 
867
    /// <returns>The deserialized object from the Json string.</returns>
 
868
    public static T DeserializeObject<T>(string value)
 
869
    {
 
870
      return DeserializeObject<T>(value, (JsonSerializerSettings) null);
 
871
    }
 
872
 
 
873
    /// <summary>
 
874
    /// Deserializes the JSON to the given anonymous type.
 
875
    /// </summary>
 
876
    /// <typeparam name="T">
 
877
    /// The anonymous type to deserialize to. This can't be specified
 
878
    /// traditionally and must be infered from the anonymous type passed
 
879
    /// as a parameter.
 
880
    /// </typeparam>
 
881
    /// <param name="value">The JSON to deserialize.</param>
 
882
    /// <param name="anonymousTypeObject">The anonymous type object.</param>
 
883
    /// <returns>The deserialized anonymous type from the JSON string.</returns>
 
884
    public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
 
885
    {
 
886
      return DeserializeObject<T>(value);
 
887
    }
 
888
 
 
889
    /// <summary>
 
890
    /// Deserializes the JSON to the specified .NET type.
 
891
    /// </summary>
 
892
    /// <typeparam name="T">The type of the object to deserialize to.</typeparam>
 
893
    /// <param name="value">The JSON to deserialize.</param>
 
894
    /// <param name="converters">Converters to use while deserializing.</param>
 
895
    /// <returns>The deserialized object from the JSON string.</returns>
 
896
    public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
 
897
    {
 
898
      return (T) DeserializeObject(value, typeof (T), converters);
 
899
    }
 
900
 
 
901
    /// <summary>
 
902
    /// Deserializes the JSON to the specified .NET type.
 
903
    /// </summary>
 
904
    /// <typeparam name="T">The type of the object to deserialize to.</typeparam>
 
905
    /// <param name="value">The object to deserialize.</param>
 
906
    /// <param name="settings">
 
907
    /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
 
908
    /// If this is null, default serialization settings will be is used.
 
909
    /// </param>
 
910
    /// <returns>The deserialized object from the JSON string.</returns>
 
911
    public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
 
912
    {
 
913
      return (T) DeserializeObject(value, typeof (T), settings);
 
914
    }
 
915
 
 
916
    /// <summary>
 
917
    /// Deserializes the JSON to the specified .NET type.
 
918
    /// </summary>
 
919
    /// <param name="value">The JSON to deserialize.</param>
 
920
    /// <param name="type">The type of the object to deserialize.</param>
 
921
    /// <param name="converters">Converters to use while deserializing.</param>
 
922
    /// <returns>The deserialized object from the JSON string.</returns>
 
923
    public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
 
924
    {
 
925
      JsonSerializerSettings settings = (converters != null && converters.Length > 0)
 
926
                                          ? new JsonSerializerSettings {Converters = converters}
 
927
                                          : null;
 
928
 
 
929
      return DeserializeObject(value, type, settings);
 
930
    }
 
931
 
 
932
    /// <summary>
 
933
    /// Deserializes the JSON to the specified .NET type.
 
934
    /// </summary>
 
935
    /// <param name="value">The JSON to deserialize.</param>
 
936
    /// <param name="type">The type of the object to deserialize to.</param>
 
937
    /// <param name="settings">
 
938
    /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
 
939
    /// If this is null, default serialization settings will be is used.
 
940
    /// </param>
 
941
    /// <returns>The deserialized object from the JSON string.</returns>
 
942
    public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
 
943
    {
 
944
      ValidationUtils.ArgumentNotNull(value, "value");
 
945
 
 
946
      StringReader sr = new StringReader(value);
 
947
      JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
 
948
 
 
949
      // by default DeserializeObject should check for additional content
 
950
      if (!jsonSerializer.IsCheckAdditionalContentSet())
 
951
        jsonSerializer.CheckAdditionalContent = true;
 
952
 
 
953
      return jsonSerializer.Deserialize(new JsonTextReader(sr), type);
 
954
    }
 
955
 
 
956
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
 
957
    /// <summary>
 
958
    /// Asynchronously deserializes the JSON to the specified .NET type.
 
959
    /// </summary>
 
960
    /// <typeparam name="T">The type of the object to deserialize to.</typeparam>
 
961
    /// <param name="value">The JSON to deserialize.</param>
 
962
    /// <returns>
 
963
    /// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
 
964
    /// </returns>
 
965
    public static Task<T> DeserializeObjectAsync<T>(string value)
 
966
    {
 
967
      return DeserializeObjectAsync<T>(value, null);
 
968
    }
 
969
 
 
970
    /// <summary>
 
971
    /// Asynchronously deserializes the JSON to the specified .NET type.
 
972
    /// </summary>
 
973
    /// <typeparam name="T">The type of the object to deserialize to.</typeparam>
 
974
    /// <param name="value">The JSON to deserialize.</param>
 
975
    /// <param name="settings">
 
976
    /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
 
977
    /// If this is null, default serialization settings will be is used.
 
978
    /// </param>
 
979
    /// <returns>
 
980
    /// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
 
981
    /// </returns>
 
982
    public static Task<T> DeserializeObjectAsync<T>(string value, JsonSerializerSettings settings)
 
983
    {
 
984
      return Task.Factory.StartNew(() => DeserializeObject<T>(value, settings));
 
985
    }
 
986
 
 
987
    /// <summary>
 
988
    /// Asynchronously deserializes the JSON to the specified .NET type.
 
989
    /// </summary>
 
990
    /// <param name="value">The JSON to deserialize.</param>
 
991
    /// <returns>
 
992
    /// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
 
993
    /// </returns>
 
994
    public static Task<object> DeserializeObjectAsync(string value)
 
995
    {
 
996
      return DeserializeObjectAsync(value, null, null);
 
997
    }
 
998
 
 
999
    /// <summary>
 
1000
    /// Asynchronously deserializes the JSON to the specified .NET type.
 
1001
    /// </summary>
 
1002
    /// <param name="value">The JSON to deserialize.</param>
 
1003
    /// <param name="type">The type of the object to deserialize to.</param>
 
1004
    /// <param name="settings">
 
1005
    /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
 
1006
    /// If this is null, default serialization settings will be is used.
 
1007
    /// </param>
 
1008
    /// <returns>
 
1009
    /// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
 
1010
    /// </returns>
 
1011
    public static Task<object> DeserializeObjectAsync(string value, Type type, JsonSerializerSettings settings)
 
1012
    {
 
1013
      return Task.Factory.StartNew(() => DeserializeObject(value, type, settings));
 
1014
    }
 
1015
#endif
 
1016
    #endregion
 
1017
 
 
1018
    /// <summary>
 
1019
    /// Populates the object with values from the JSON string.
 
1020
    /// </summary>
 
1021
    /// <param name="value">The JSON to populate values from.</param>
 
1022
    /// <param name="target">The target object to populate values onto.</param>
 
1023
    public static void PopulateObject(string value, object target)
 
1024
    {
 
1025
      PopulateObject(value, target, null);
 
1026
    }
 
1027
 
 
1028
    /// <summary>
 
1029
    /// Populates the object with values from the JSON string.
 
1030
    /// </summary>
 
1031
    /// <param name="value">The JSON to populate values from.</param>
 
1032
    /// <param name="target">The target object to populate values onto.</param>
 
1033
    /// <param name="settings">
 
1034
    /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
 
1035
    /// If this is null, default serialization settings will be is used.
 
1036
    /// </param>
 
1037
    public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
 
1038
    {
 
1039
      StringReader sr = new StringReader(value);
 
1040
      JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
 
1041
 
 
1042
      using (JsonReader jsonReader = new JsonTextReader(sr))
 
1043
      {
 
1044
        jsonSerializer.Populate(jsonReader, target);
 
1045
 
 
1046
        if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
 
1047
          throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
 
1048
      }
 
1049
    }
 
1050
 
 
1051
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
 
1052
    /// <summary>
 
1053
    /// Asynchronously populates the object with values from the JSON string.
 
1054
    /// </summary>
 
1055
    /// <param name="value">The JSON to populate values from.</param>
 
1056
    /// <param name="target">The target object to populate values onto.</param>
 
1057
    /// <param name="settings">
 
1058
    /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
 
1059
    /// If this is null, default serialization settings will be is used.
 
1060
    /// </param>
 
1061
    /// <returns>
 
1062
    /// A task that represents the asynchronous populate operation.
 
1063
    /// </returns>
 
1064
    public static Task PopulateObjectAsync(string value, object target, JsonSerializerSettings settings)
 
1065
    {
 
1066
      return Task.Factory.StartNew(() => PopulateObject(value, target, settings));
 
1067
    }
 
1068
#endif
 
1069
 
 
1070
#if !(SILVERLIGHT || PORTABLE || NETFX_CORE)
 
1071
    /// <summary>
 
1072
    /// Serializes the XML node to a JSON string.
 
1073
    /// </summary>
 
1074
    /// <param name="node">The node to serialize.</param>
 
1075
    /// <returns>A JSON string of the XmlNode.</returns>
 
1076
    public static string SerializeXmlNode(XmlNode node)
 
1077
    {
 
1078
      return SerializeXmlNode(node, Formatting.None);
 
1079
    }
 
1080
 
 
1081
    /// <summary>
 
1082
    /// Serializes the XML node to a JSON string.
 
1083
    /// </summary>
 
1084
    /// <param name="node">The node to serialize.</param>
 
1085
    /// <param name="formatting">Indicates how the output is formatted.</param>
 
1086
    /// <returns>A JSON string of the XmlNode.</returns>
 
1087
    public static string SerializeXmlNode(XmlNode node, Formatting formatting)
 
1088
    {
 
1089
      XmlNodeConverter converter = new XmlNodeConverter();
 
1090
 
 
1091
      return SerializeObject(node, formatting, converter);
 
1092
    }
 
1093
 
 
1094
    /// <summary>
 
1095
    /// Serializes the XML node to a JSON string.
 
1096
    /// </summary>
 
1097
    /// <param name="node">The node to serialize.</param>
 
1098
    /// <param name="formatting">Indicates how the output is formatted.</param>
 
1099
    /// <param name="omitRootObject">Omits writing the root object.</param>
 
1100
    /// <returns>A JSON string of the XmlNode.</returns>
 
1101
    public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject)
 
1102
    {
 
1103
      XmlNodeConverter converter = new XmlNodeConverter {OmitRootObject = omitRootObject};
 
1104
 
 
1105
      return SerializeObject(node, formatting, converter);
 
1106
    }
 
1107
 
 
1108
    /// <summary>
 
1109
    /// Deserializes the XmlNode from a JSON string.
 
1110
    /// </summary>
 
1111
    /// <param name="value">The JSON string.</param>
 
1112
    /// <returns>The deserialized XmlNode</returns>
 
1113
    public static XmlDocument DeserializeXmlNode(string value)
 
1114
    {
 
1115
      return DeserializeXmlNode(value, null);
 
1116
    }
 
1117
 
 
1118
    /// <summary>
 
1119
    /// Deserializes the XmlNode from a JSON string nested in a root elment.
 
1120
    /// </summary>
 
1121
    /// <param name="value">The JSON string.</param>
 
1122
    /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
 
1123
    /// <returns>The deserialized XmlNode</returns>
 
1124
    public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName)
 
1125
    {
 
1126
      return DeserializeXmlNode(value, deserializeRootElementName, false);
 
1127
    }
 
1128
 
 
1129
    /// <summary>
 
1130
    /// Deserializes the XmlNode from a JSON string nested in a root elment.
 
1131
    /// </summary>
 
1132
    /// <param name="value">The JSON string.</param>
 
1133
    /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
 
1134
    /// <param name="writeArrayAttribute">
 
1135
    /// A flag to indicate whether to write the Json.NET array attribute.
 
1136
    /// This attribute helps preserve arrays when converting the written XML back to JSON.
 
1137
    /// </param>
 
1138
    /// <returns>The deserialized XmlNode</returns>
 
1139
    public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
 
1140
    {
 
1141
      XmlNodeConverter converter = new XmlNodeConverter();
 
1142
      converter.DeserializeRootElementName = deserializeRootElementName;
 
1143
      converter.WriteArrayAttribute = writeArrayAttribute;
 
1144
 
 
1145
      return (XmlDocument) DeserializeObject(value, typeof (XmlDocument), converter);
 
1146
    }
 
1147
#endif
 
1148
 
 
1149
#if !NET20 && (!(SILVERLIGHT || PORTABLE) || WINDOWS_PHONE)
 
1150
    /// <summary>
 
1151
    /// Serializes the <see cref="XNode"/> to a JSON string.
 
1152
    /// </summary>
 
1153
    /// <param name="node">The node to convert to JSON.</param>
 
1154
    /// <returns>A JSON string of the XNode.</returns>
 
1155
    public static string SerializeXNode(XObject node)
 
1156
    {
 
1157
      return SerializeXNode(node, Formatting.None);
 
1158
    }
 
1159
 
 
1160
    /// <summary>
 
1161
    /// Serializes the <see cref="XNode"/> to a JSON string.
 
1162
    /// </summary>
 
1163
    /// <param name="node">The node to convert to JSON.</param>
 
1164
    /// <param name="formatting">Indicates how the output is formatted.</param>
 
1165
    /// <returns>A JSON string of the XNode.</returns>
 
1166
    public static string SerializeXNode(XObject node, Formatting formatting)
 
1167
    {
 
1168
      return SerializeXNode(node, formatting, false);
 
1169
    }
 
1170
 
 
1171
    /// <summary>
 
1172
    /// Serializes the <see cref="XNode"/> to a JSON string.
 
1173
    /// </summary>
 
1174
    /// <param name="node">The node to serialize.</param>
 
1175
    /// <param name="formatting">Indicates how the output is formatted.</param>
 
1176
    /// <param name="omitRootObject">Omits writing the root object.</param>
 
1177
    /// <returns>A JSON string of the XNode.</returns>
 
1178
    public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject)
 
1179
    {
 
1180
      XmlNodeConverter converter = new XmlNodeConverter {OmitRootObject = omitRootObject};
 
1181
 
 
1182
      return SerializeObject(node, formatting, converter);
 
1183
    }
 
1184
 
 
1185
    /// <summary>
 
1186
    /// Deserializes the <see cref="XNode"/> from a JSON string.
 
1187
    /// </summary>
 
1188
    /// <param name="value">The JSON string.</param>
 
1189
    /// <returns>The deserialized XNode</returns>
 
1190
    public static XDocument DeserializeXNode(string value)
 
1191
    {
 
1192
      return DeserializeXNode(value, null);
 
1193
    }
 
1194
 
 
1195
    /// <summary>
 
1196
    /// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment.
 
1197
    /// </summary>
 
1198
    /// <param name="value">The JSON string.</param>
 
1199
    /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
 
1200
    /// <returns>The deserialized XNode</returns>
 
1201
    public static XDocument DeserializeXNode(string value, string deserializeRootElementName)
 
1202
    {
 
1203
      return DeserializeXNode(value, deserializeRootElementName, false);
 
1204
    }
 
1205
 
 
1206
    /// <summary>
 
1207
    /// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment.
 
1208
    /// </summary>
 
1209
    /// <param name="value">The JSON string.</param>
 
1210
    /// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
 
1211
    /// <param name="writeArrayAttribute">
 
1212
    /// A flag to indicate whether to write the Json.NET array attribute.
 
1213
    /// This attribute helps preserve arrays when converting the written XML back to JSON.
 
1214
    /// </param>
 
1215
    /// <returns>The deserialized XNode</returns>
 
1216
    public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
 
1217
    {
 
1218
      XmlNodeConverter converter = new XmlNodeConverter();
 
1219
      converter.DeserializeRootElementName = deserializeRootElementName;
 
1220
      converter.WriteArrayAttribute = writeArrayAttribute;
 
1221
 
 
1222
      return (XDocument) DeserializeObject(value, typeof (XDocument), converter);
 
1223
    }
 
1224
#endif
 
1225
  }
 
1226
}
 
 
b'\\ No newline at end of file'