2
// Copyright (c) 2007 James Newton-King
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
13
// The above copyright notice and this permission notice shall be
14
// included in all copies or substantial portions of the Software.
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.
28
using System.Globalization;
29
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
30
using System.Threading.Tasks;
32
using Newtonsoft.Json.Utilities;
34
using Newtonsoft.Json.Converters;
36
#if !NET20 && (!SILVERLIGHT || WINDOWS_PHONE) && !PORTABLE
37
using System.Xml.Linq;
40
using IConvertible = Newtonsoft.Json.Utilities.Convertible;
43
namespace Newtonsoft.Json
46
/// Provides methods for converting between common language runtime types and JSON types.
49
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="SerializeObject" title="Serializing and Deserializing JSON with JsonConvert" />
51
public static class JsonConvert
54
/// Represents JavaScript's boolean value true as a string. This field is read-only.
56
public static readonly string True = "true";
59
/// Represents JavaScript's boolean value false as a string. This field is read-only.
61
public static readonly string False = "false";
64
/// Represents JavaScript's null as a string. This field is read-only.
66
public static readonly string Null = "null";
69
/// Represents JavaScript's undefined as a string. This field is read-only.
71
public static readonly string Undefined = "undefined";
74
/// Represents JavaScript's positive infinity as a string. This field is read-only.
76
public static readonly string PositiveInfinity = "Infinity";
79
/// Represents JavaScript's negative infinity as a string. This field is read-only.
81
public static readonly string NegativeInfinity = "-Infinity";
84
/// Represents JavaScript's NaN as a string. This field is read-only.
86
public static readonly string NaN = "NaN";
88
internal static readonly long InitialJavaScriptDateTicks = 621355968000000000;
91
/// Converts the <see cref="DateTime"/> to its JSON string representation.
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)
97
return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
101
/// Converts the <see cref="DateTime"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
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)
109
DateTime updatedDateTime = EnsureDateTime(value, timeZoneHandling);
111
using (StringWriter writer = StringUtils.CreateStringWriter(64))
113
WriteDateTimeString(writer, updatedDateTime, updatedDateTime.GetUtcOffset(), updatedDateTime.Kind, format, '"');
114
return writer.ToString();
118
internal static DateTime EnsureDateTime(DateTime value, DateTimeZoneHandling timeZone)
122
case DateTimeZoneHandling.Local:
123
value = SwitchToLocalTime(value);
125
case DateTimeZoneHandling.Utc:
126
value = SwitchToUtcTime(value);
128
case DateTimeZoneHandling.Unspecified:
129
value = new DateTime(value.Ticks, DateTimeKind.Unspecified);
131
case DateTimeZoneHandling.RoundtripKind:
134
throw new ArgumentException("Invalid date time handling value.");
140
#if !PocketPC && !NET20
142
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
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)
148
return ToString(value, DateFormatHandling.IsoDateFormat);
152
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
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)
159
return ToString(value, format, '"');
162
internal static string ToString(DateTimeOffset value, DateFormatHandling format, char quoteChar)
164
using (StringWriter writer = StringUtils.CreateStringWriter(64))
166
WriteDateTimeString(writer, (format == DateFormatHandling.IsoDateFormat) ? value.DateTime : value.UtcDateTime, value.Offset, DateTimeKind.Local, format, quoteChar);
167
return writer.ToString();
172
internal static void WriteDateTimeString(TextWriter writer, DateTime value, DateFormatHandling format, char quoteChar)
174
WriteDateTimeString(writer, value, value.GetUtcOffset(), value.Kind, format, quoteChar);
177
internal static void WriteDateTimeString(TextWriter writer, DateTime value, TimeSpan offset, DateTimeKind kind, DateFormatHandling format, char quoteChar)
179
if (format == DateFormatHandling.MicrosoftDateFormat)
181
long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value, offset);
183
writer.Write(quoteChar);
184
writer.Write(@"\/Date(");
185
writer.Write(javaScriptTicks);
189
case DateTimeKind.Unspecified:
190
if (value != DateTime.MaxValue && value != DateTime.MinValue)
191
WriteDateTimeOffset(writer, offset, format);
193
case DateTimeKind.Local:
194
WriteDateTimeOffset(writer, offset, format);
198
writer.Write(@")\/");
199
writer.Write(quoteChar);
203
writer.Write(quoteChar);
204
writer.Write(value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFF", CultureInfo.InvariantCulture));
208
case DateTimeKind.Local:
209
WriteDateTimeOffset(writer, offset, format);
211
case DateTimeKind.Utc:
217
writer.Write(quoteChar);
221
internal static void WriteDateTimeOffset(TextWriter writer, TimeSpan offset, DateFormatHandling format)
223
writer.Write((offset.Ticks >= 0L) ? "+" : "-");
225
int absHours = Math.Abs(offset.Hours);
228
writer.Write(absHours);
230
if (format == DateFormatHandling.IsoDateFormat)
233
int absMinutes = Math.Abs(offset.Minutes);
236
writer.Write(absMinutes);
239
private static long ToUniversalTicks(DateTime dateTime)
241
if (dateTime.Kind == DateTimeKind.Utc)
242
return dateTime.Ticks;
244
return ToUniversalTicks(dateTime, dateTime.GetUtcOffset());
247
private static long ToUniversalTicks(DateTime dateTime, TimeSpan offset)
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;
254
long ticks = dateTime.Ticks - offset.Ticks;
255
if (ticks > 3155378975999999999L)
256
return 3155378975999999999L;
264
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, TimeSpan offset)
266
long universialTicks = ToUniversalTicks(dateTime, offset);
268
return UniversialTicksToJavaScriptTicks(universialTicks);
271
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime)
273
return ConvertDateTimeToJavaScriptTicks(dateTime, true);
276
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, bool convertToUtc)
278
long ticks = (convertToUtc) ? ToUniversalTicks(dateTime) : dateTime.Ticks;
280
return UniversialTicksToJavaScriptTicks(ticks);
283
private static long UniversialTicksToJavaScriptTicks(long universialTicks)
285
long javaScriptTicks = (universialTicks - InitialJavaScriptDateTicks)/10000;
287
return javaScriptTicks;
290
internal static DateTime ConvertJavaScriptTicksToDateTime(long javaScriptTicks)
292
DateTime dateTime = new DateTime((javaScriptTicks*10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc);
297
private static DateTime SwitchToLocalTime(DateTime value)
301
case DateTimeKind.Unspecified:
302
return new DateTime(value.Ticks, DateTimeKind.Local);
304
case DateTimeKind.Utc:
305
return value.ToLocalTime();
307
case DateTimeKind.Local:
313
private static DateTime SwitchToUtcTime(DateTime value)
317
case DateTimeKind.Unspecified:
318
return new DateTime(value.Ticks, DateTimeKind.Utc);
320
case DateTimeKind.Utc:
323
case DateTimeKind.Local:
324
return value.ToUniversalTime();
330
/// Converts the <see cref="Boolean"/> to its JSON string representation.
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)
336
return (value) ? True : False;
340
/// Converts the <see cref="Char"/> to its JSON string representation.
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)
346
return ToString(char.ToString(value));
350
/// Converts the <see cref="Enum"/> to its JSON string representation.
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)
356
return value.ToString("D");
360
/// Converts the <see cref="Int32"/> to its JSON string representation.
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)
366
return value.ToString(null, CultureInfo.InvariantCulture);
370
/// Converts the <see cref="Int16"/> to its JSON string representation.
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)
376
return value.ToString(null, CultureInfo.InvariantCulture);
380
/// Converts the <see cref="UInt16"/> to its JSON string representation.
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)
387
return value.ToString(null, CultureInfo.InvariantCulture);
391
/// Converts the <see cref="UInt32"/> to its JSON string representation.
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)
398
return value.ToString(null, CultureInfo.InvariantCulture);
402
/// Converts the <see cref="Int64"/> to its JSON string representation.
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)
408
return value.ToString(null, CultureInfo.InvariantCulture);
412
/// Converts the <see cref="UInt64"/> to its JSON string representation.
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)
419
return value.ToString(null, CultureInfo.InvariantCulture);
423
/// Converts the <see cref="Single"/> to its JSON string representation.
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)
429
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
433
/// Converts the <see cref="Double"/> to its JSON string representation.
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)
439
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
442
private static string EnsureDecimalPlace(double value, string text)
444
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1)
450
private static string EnsureDecimalPlace(string text)
452
if (text.IndexOf('.') != -1)
459
/// Converts the <see cref="Byte"/> to its JSON string representation.
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)
465
return value.ToString(null, CultureInfo.InvariantCulture);
469
/// Converts the <see cref="SByte"/> to its JSON string representation.
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)
476
return value.ToString(null, CultureInfo.InvariantCulture);
480
/// Converts the <see cref="Decimal"/> to its JSON string representation.
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)
486
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
490
/// Converts the <see cref="Guid"/> to its JSON string representation.
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)
496
return ToString(value, '"');
499
internal static string ToString(Guid value, char quoteChar)
503
#if !(NETFX_CORE || PORTABLE)
504
text = value.ToString("D", CultureInfo.InvariantCulture);
506
text = value.ToString("D");
509
return quoteChar + text + quoteChar;
513
/// Converts the <see cref="TimeSpan"/> to its JSON string representation.
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)
519
return ToString(value, '"');
522
internal static string ToString(TimeSpan value, char quoteChar)
524
return ToString(value.ToString(), quoteChar);
528
/// Converts the <see cref="Uri"/> to its JSON string representation.
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)
537
return ToString(value, '"');
540
internal static string ToString(Uri value, char quoteChar)
542
return ToString(value.ToString(), quoteChar);
546
/// Converts the <see cref="String"/> to its JSON string representation.
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)
552
return ToString(value, '"');
556
/// Converts the <see cref="String"/> to its JSON string representation.
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)
563
if (delimiter != '"' && delimiter != '\'')
564
throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter");
566
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true);
570
/// Converts the <see cref="Object"/> to its JSON string representation.
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)
579
IConvertible convertible = ConvertUtils.ToConvertible(value);
581
if (convertible != null)
583
switch (convertible.GetTypeCode())
585
case TypeCode.String:
586
return ToString(convertible.ToString(CultureInfo.InvariantCulture));
588
return ToString(convertible.ToChar(CultureInfo.InvariantCulture));
589
case TypeCode.Boolean:
590
return ToString(convertible.ToBoolean(CultureInfo.InvariantCulture));
592
return ToString(convertible.ToSByte(CultureInfo.InvariantCulture));
594
return ToString(convertible.ToInt16(CultureInfo.InvariantCulture));
595
case TypeCode.UInt16:
596
return ToString(convertible.ToUInt16(CultureInfo.InvariantCulture));
598
return ToString(convertible.ToInt32(CultureInfo.InvariantCulture));
600
return ToString(convertible.ToByte(CultureInfo.InvariantCulture));
601
case TypeCode.UInt32:
602
return ToString(convertible.ToUInt32(CultureInfo.InvariantCulture));
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:
621
#if !PocketPC && !NET20
622
else if (value is DateTimeOffset)
624
return ToString((DateTimeOffset) value);
627
else if (value is Guid)
629
return ToString((Guid) value);
631
else if (value is Uri)
633
return ToString((Uri) value);
635
else if (value is TimeSpan)
637
return ToString((TimeSpan) value);
640
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
643
private static bool IsJsonPrimitiveTypeCode(TypeCode typeCode)
647
case TypeCode.String:
649
case TypeCode.Boolean:
652
case TypeCode.UInt16:
655
case TypeCode.UInt32:
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:
671
internal static bool IsJsonPrimitiveType(Type type)
673
if (ReflectionUtils.IsNullableType(type))
674
type = Nullable.GetUnderlyingType(type);
676
#if !PocketPC && !NET20
677
if (type == typeof (DateTimeOffset))
680
if (type == typeof (byte[]))
682
if (type == typeof (Uri))
684
if (type == typeof (TimeSpan))
686
if (type == typeof (Guid))
689
return IsJsonPrimitiveTypeCode(ConvertUtils.GetTypeCode(type));
694
/// Serializes the specified object to a JSON string.
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)
700
return SerializeObject(value, Formatting.None, (JsonSerializerSettings) null);
704
/// Serializes the specified object to a JSON string.
706
/// <param name="value">The object to serialize.</param>
707
/// <param name="formatting">Indicates how the output is formatted.</param>
709
/// A JSON string representation of the object.
711
public static string SerializeObject(object value, Formatting formatting)
713
return SerializeObject(value, formatting, (JsonSerializerSettings) null);
717
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
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)
724
return SerializeObject(value, Formatting.None, converters);
728
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
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)
736
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
737
? new JsonSerializerSettings {Converters = converters}
740
return SerializeObject(value, formatting, settings);
744
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
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>
750
/// A JSON string representation of the object.
752
public static string SerializeObject(object value, JsonSerializerSettings settings)
754
return SerializeObject(value, Formatting.None, settings);
758
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
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>
765
/// A JSON string representation of the object.
767
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
769
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
771
StringBuilder sb = new StringBuilder(256);
772
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
773
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
775
jsonWriter.Formatting = formatting;
777
jsonSerializer.Serialize(jsonWriter, value);
780
return sw.ToString();
783
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
785
/// Asynchronously serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
787
/// <param name="value">The object to serialize.</param>
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.
791
public static Task<string> SerializeObjectAsync(object value)
793
return SerializeObjectAsync(value, Formatting.None, null);
797
/// Asynchronously serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
799
/// <param name="value">The object to serialize.</param>
800
/// <param name="formatting">Indicates how the output is formatted.</param>
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.
804
public static Task<string> SerializeObjectAsync(object value, Formatting formatting)
806
return SerializeObjectAsync(value, formatting, null);
810
/// Asynchronously serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
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>
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.
819
public static Task<string> SerializeObjectAsync(object value, Formatting formatting, JsonSerializerSettings settings)
821
return Task.Factory.StartNew(() => SerializeObject(value, formatting, settings));
828
/// Deserializes the JSON to a .NET object.
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)
834
return DeserializeObject(value, null, (JsonSerializerSettings) null);
838
/// Deserializes the JSON to a .NET object.
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.
845
/// <returns>The deserialized object from the JSON string.</returns>
846
public static object DeserializeObject(string value, JsonSerializerSettings settings)
848
return DeserializeObject(value, null, settings);
852
/// Deserializes the JSON to the specified .NET type.
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)
859
return DeserializeObject(value, type, (JsonSerializerSettings) null);
863
/// Deserializes the JSON to the specified .NET type.
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)
870
return DeserializeObject<T>(value, (JsonSerializerSettings) null);
874
/// Deserializes the JSON to the given anonymous type.
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
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)
886
return DeserializeObject<T>(value);
890
/// Deserializes the JSON to the specified .NET type.
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)
898
return (T) DeserializeObject(value, typeof (T), converters);
902
/// Deserializes the JSON to the specified .NET type.
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.
910
/// <returns>The deserialized object from the JSON string.</returns>
911
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
913
return (T) DeserializeObject(value, typeof (T), settings);
917
/// Deserializes the JSON to the specified .NET type.
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)
925
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
926
? new JsonSerializerSettings {Converters = converters}
929
return DeserializeObject(value, type, settings);
933
/// Deserializes the JSON to the specified .NET type.
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.
941
/// <returns>The deserialized object from the JSON string.</returns>
942
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
944
ValidationUtils.ArgumentNotNull(value, "value");
946
StringReader sr = new StringReader(value);
947
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
949
// by default DeserializeObject should check for additional content
950
if (!jsonSerializer.IsCheckAdditionalContentSet())
951
jsonSerializer.CheckAdditionalContent = true;
953
return jsonSerializer.Deserialize(new JsonTextReader(sr), type);
956
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
958
/// Asynchronously deserializes the JSON to the specified .NET type.
960
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
961
/// <param name="value">The JSON to deserialize.</param>
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.
965
public static Task<T> DeserializeObjectAsync<T>(string value)
967
return DeserializeObjectAsync<T>(value, null);
971
/// Asynchronously deserializes the JSON to the specified .NET type.
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.
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.
982
public static Task<T> DeserializeObjectAsync<T>(string value, JsonSerializerSettings settings)
984
return Task.Factory.StartNew(() => DeserializeObject<T>(value, settings));
988
/// Asynchronously deserializes the JSON to the specified .NET type.
990
/// <param name="value">The JSON to deserialize.</param>
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.
994
public static Task<object> DeserializeObjectAsync(string value)
996
return DeserializeObjectAsync(value, null, null);
1000
/// Asynchronously deserializes the JSON to the specified .NET type.
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.
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.
1011
public static Task<object> DeserializeObjectAsync(string value, Type type, JsonSerializerSettings settings)
1013
return Task.Factory.StartNew(() => DeserializeObject(value, type, settings));
1019
/// Populates the object with values from the JSON string.
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)
1025
PopulateObject(value, target, null);
1029
/// Populates the object with values from the JSON string.
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.
1037
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
1039
StringReader sr = new StringReader(value);
1040
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
1042
using (JsonReader jsonReader = new JsonTextReader(sr))
1044
jsonSerializer.Populate(jsonReader, target);
1046
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
1047
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
1051
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
1053
/// Asynchronously populates the object with values from the JSON string.
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.
1062
/// A task that represents the asynchronous populate operation.
1064
public static Task PopulateObjectAsync(string value, object target, JsonSerializerSettings settings)
1066
return Task.Factory.StartNew(() => PopulateObject(value, target, settings));
1070
#if !(SILVERLIGHT || PORTABLE || NETFX_CORE)
1072
/// Serializes the XML node to a JSON string.
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)
1078
return SerializeXmlNode(node, Formatting.None);
1082
/// Serializes the XML node to a JSON string.
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)
1089
XmlNodeConverter converter = new XmlNodeConverter();
1091
return SerializeObject(node, formatting, converter);
1095
/// Serializes the XML node to a JSON string.
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)
1103
XmlNodeConverter converter = new XmlNodeConverter {OmitRootObject = omitRootObject};
1105
return SerializeObject(node, formatting, converter);
1109
/// Deserializes the XmlNode from a JSON string.
1111
/// <param name="value">The JSON string.</param>
1112
/// <returns>The deserialized XmlNode</returns>
1113
public static XmlDocument DeserializeXmlNode(string value)
1115
return DeserializeXmlNode(value, null);
1119
/// Deserializes the XmlNode from a JSON string nested in a root elment.
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)
1126
return DeserializeXmlNode(value, deserializeRootElementName, false);
1130
/// Deserializes the XmlNode from a JSON string nested in a root elment.
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.
1138
/// <returns>The deserialized XmlNode</returns>
1139
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
1141
XmlNodeConverter converter = new XmlNodeConverter();
1142
converter.DeserializeRootElementName = deserializeRootElementName;
1143
converter.WriteArrayAttribute = writeArrayAttribute;
1145
return (XmlDocument) DeserializeObject(value, typeof (XmlDocument), converter);
1149
#if !NET20 && (!(SILVERLIGHT || PORTABLE) || WINDOWS_PHONE)
1151
/// Serializes the <see cref="XNode"/> to a JSON string.
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)
1157
return SerializeXNode(node, Formatting.None);
1161
/// Serializes the <see cref="XNode"/> to a JSON string.
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)
1168
return SerializeXNode(node, formatting, false);
1172
/// Serializes the <see cref="XNode"/> to a JSON string.
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)
1180
XmlNodeConverter converter = new XmlNodeConverter {OmitRootObject = omitRootObject};
1182
return SerializeObject(node, formatting, converter);
1186
/// Deserializes the <see cref="XNode"/> from a JSON string.
1188
/// <param name="value">The JSON string.</param>
1189
/// <returns>The deserialized XNode</returns>
1190
public static XDocument DeserializeXNode(string value)
1192
return DeserializeXNode(value, null);
1196
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment.
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)
1203
return DeserializeXNode(value, deserializeRootElementName, false);
1207
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment.
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.
1215
/// <returns>The deserialized XNode</returns>
1216
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
1218
XmlNodeConverter converter = new XmlNodeConverter();
1219
converter.DeserializeRootElementName = deserializeRootElementName;
1220
converter.WriteArrayAttribute = writeArrayAttribute;
1222
return (XDocument) DeserializeObject(value, typeof (XDocument), converter);
b'\\ No newline at end of file'