Permalink

Newtonsoft.Json uses LINQ-TO-JSON API internally to loop through the properties or objects in the given JSON string. Before understanding whether we need to use Newtonsoft.Json.JsonConvert.DeserializeObjectorNewtonsoft.Json.Linq.JToken.Parse we need to know following some of the built-in classes. JToken – This is the abstract base class.

Join GitHub today

Newtonsoft

GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

Newtonsoft json deserialize stringSign up
Find file Copy path
JamesNKFix allocating empty arrays and more nullable warningsd75074fAug 19, 2019
6 contributors
#regionLicense
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the 'Software'), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
usingSystem;
usingSystem.IO;
usingSystem.Globalization;
#ifHAVE_BIG_INTEGER
usingSystem.Numerics;
#endif
usingNewtonsoft.Json.Linq;
usingNewtonsoft.Json.Utilities;
usingSystem.Xml;
usingNewtonsoft.Json.Converters;
usingNewtonsoft.Json.Serialization;
usingSystem.Text;
usingSystem.Diagnostics;
usingSystem.Runtime.CompilerServices;
usingSystem.Diagnostics.CodeAnalysis;
#ifHAVE_XLINQ
usingSystem.Xml.Linq;
#endif
namespaceNewtonsoft.Json
{
/// <summary>
/// Provides methods for converting between .NET types and JSON types.
/// </summary>
/// <example>
/// <codelang='cs'source='..SrcNewtonsoft.Json.TestsDocumentationSerializationTests.cs'region='SerializeObject'title='Serializing and Deserializing JSON with JsonConvert' />
/// </example>
publicstaticclassJsonConvert
{
/// <summary>
/// Gets or sets a function that creates default <seecref='JsonSerializerSettings'/>.
/// Default settings are automatically used by serialization methods on <seecref='JsonConvert'/>,
/// and <seecref='JToken.ToObject{T}()'/> and <seecref='JToken.FromObject(object)'/> on <seecref='JToken'/>.
/// To serialize without using any default settings create a <seecref='JsonSerializer'/> with
/// <seecref='JsonSerializer.Create()'/>.
/// </summary>
publicstaticFunc<JsonSerializerSettings>? DefaultSettings { get; set; }
/// <summary>
/// Represents JavaScript's boolean value <c>true</c> as a string. This field is read-only.
/// </summary>
publicstaticreadonlystringTrue='true';
/// <summary>
/// Represents JavaScript's boolean value <c>false</c> as a string. This field is read-only.
/// </summary>
publicstaticreadonlystringFalse='false';
/// <summary>
/// Represents JavaScript's <c>null</c> as a string. This field is read-only.
/// </summary>
publicstaticreadonlystringNull='null';
/// <summary>
/// Represents JavaScript's <c>undefined</c> as a string. This field is read-only.
/// </summary>
publicstaticreadonlystringUndefined='undefined';
/// <summary>
/// Represents JavaScript's positive infinity as a string. This field is read-only.
/// </summary>
publicstaticreadonlystringPositiveInfinity='Infinity';
/// <summary>
/// Represents JavaScript's negative infinity as a string. This field is read-only.
/// </summary>
publicstaticreadonlystringNegativeInfinity='-Infinity';
/// <summary>
/// Represents JavaScript's <c>NaN</c> as a string. This field is read-only.
/// </summary>
publicstaticreadonlystringNaN='NaN';
/// <summary>
/// Converts the <seecref='DateTime'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='DateTime'/>.</returns>
publicstaticstringToString(DateTimevalue)
{
returnToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
}
/// <summary>
/// Converts the <seecref='DateTime'/> to its JSON string representation using the <seecref='DateFormatHandling'/> specified.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <paramname='format'>The format the date will be converted to.</param>
/// <paramname='timeZoneHandling'>The time zone handling when the date is converted to a string.</param>
/// <returns>A JSON string representation of the <seecref='DateTime'/>.</returns>
publicstaticstringToString(DateTimevalue, DateFormatHandlingformat, DateTimeZoneHandlingtimeZoneHandling)
{
DateTimeupdatedDateTime=DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
using (StringWriterwriter=StringUtils.CreateStringWriter(64))
{
writer.Write('');
DateTimeUtils.WriteDateTimeString(writer, updatedDateTime, format, null, CultureInfo.InvariantCulture);
writer.Write('');
returnwriter.ToString();
}
}
#ifHAVE_DATE_TIME_OFFSET
/// <summary>
/// Converts the <seecref='DateTimeOffset'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='DateTimeOffset'/>.</returns>
publicstaticstringToString(DateTimeOffsetvalue)
{
returnToString(value, DateFormatHandling.IsoDateFormat);
}
/// <summary>
/// Converts the <seecref='DateTimeOffset'/> to its JSON string representation using the <seecref='DateFormatHandling'/> specified.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <paramname='format'>The format the date will be converted to.</param>
/// <returns>A JSON string representation of the <seecref='DateTimeOffset'/>.</returns>
publicstaticstringToString(DateTimeOffsetvalue, DateFormatHandlingformat)
{
using (StringWriterwriter=StringUtils.CreateStringWriter(64))
{
writer.Write('');
DateTimeUtils.WriteDateTimeOffsetString(writer, value, format, null, CultureInfo.InvariantCulture);
writer.Write('');
returnwriter.ToString();
}
}
#endif
/// <summary>
/// Converts the <seecref='Boolean'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Boolean'/>.</returns>
publicstaticstringToString(boolvalue)
{
return (value) ?True:False;
}
/// <summary>
/// Converts the <seecref='Char'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Char'/>.</returns>
publicstaticstringToString(charvalue)
{
returnToString(char.ToString(value));
}
/// <summary>
/// Converts the <seecref='Enum'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Enum'/>.</returns>
publicstaticstringToString(Enumvalue)
{
returnvalue.ToString('D');
}
/// <summary>
/// Converts the <seecref='Int32'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Int32'/>.</returns>
publicstaticstringToString(intvalue)
{
returnvalue.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <seecref='Int16'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Int16'/>.</returns>
publicstaticstringToString(shortvalue)
{
returnvalue.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <seecref='UInt16'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='UInt16'/>.</returns>
[CLSCompliant(false)]
publicstaticstringToString(ushortvalue)
{
returnvalue.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <seecref='UInt32'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='UInt32'/>.</returns>
[CLSCompliant(false)]
publicstaticstringToString(uintvalue)
{
returnvalue.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <seecref='Int64'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Int64'/>.</returns>
publicstaticstringToString(longvalue)
{
returnvalue.ToString(null, CultureInfo.InvariantCulture);
}
#ifHAVE_BIG_INTEGER
privatestaticstringToStringInternal(BigIntegervalue)
{
returnvalue.ToString(null, CultureInfo.InvariantCulture);
}
#endif
/// <summary>
/// Converts the <seecref='UInt64'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='UInt64'/>.</returns>
[CLSCompliant(false)]
publicstaticstringToString(ulongvalue)
{
returnvalue.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <seecref='Single'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Single'/>.</returns>
publicstaticstringToString(floatvalue)
{
returnEnsureDecimalPlace(value, value.ToString('R', CultureInfo.InvariantCulture));
}
internalstaticstringToString(floatvalue, FloatFormatHandlingfloatFormatHandling, charquoteChar, boolnullable)
{
returnEnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString('R', CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
privatestaticstringEnsureFloatFormat(doublevalue, stringtext, FloatFormatHandlingfloatFormatHandling, charquoteChar, boolnullable)
{
if (floatFormatHandlingFloatFormatHandling.Symbol||!(double.IsInfinity(value) ||double.IsNaN(value)))
{
returntext;
}
if (floatFormatHandlingFloatFormatHandling.DefaultValue)
{
return (!nullable) ?'0.0':Null;
}
returnquoteChar+text+quoteChar;
}
/// <summary>
/// Converts the <seecref='Double'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Double'/>.</returns>
publicstaticstringToString(doublevalue)
{
returnEnsureDecimalPlace(value, value.ToString('R', CultureInfo.InvariantCulture));
}
internalstaticstringToString(doublevalue, FloatFormatHandlingfloatFormatHandling, charquoteChar, boolnullable)
{
returnEnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString('R', CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
}
privatestaticstringEnsureDecimalPlace(doublevalue, stringtext)
{
if (double.IsNaN(value) ||double.IsInfinity(value) ||text.IndexOf('.') !=-1||text.IndexOf('E') !=-1||text.IndexOf('e') !=-1)
{
returntext;
}
returntext+'.0';
}
privatestaticstringEnsureDecimalPlace(stringtext)
{
if (text.IndexOf('.') !=-1)
{
returntext;
}
returntext+'.0';
}
/// <summary>
/// Converts the <seecref='Byte'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Byte'/>.</returns>
publicstaticstringToString(bytevalue)
{
returnvalue.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <seecref='SByte'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='SByte'/>.</returns>
[CLSCompliant(false)]
publicstaticstringToString(sbytevalue)
{
returnvalue.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <seecref='Decimal'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Decimal'/>.</returns>
publicstaticstringToString(decimalvalue)
{
returnEnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <seecref='Guid'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Guid'/>.</returns>
publicstaticstringToString(Guidvalue)
{
returnToString(value, '');
}
internalstaticstringToString(Guidvalue, charquoteChar)
{
stringtext;
stringqc;
#ifHAVE_CHAR_TO_STRING_WITH_CULTURE
text=value.ToString('D', CultureInfo.InvariantCulture);
qc=quoteChar.ToString(CultureInfo.InvariantCulture);
#else
text=value.ToString('D');
qc=quoteChar.ToString();
#endif
returnqc+text+qc;
}
/// <summary>
/// Converts the <seecref='TimeSpan'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='TimeSpan'/>.</returns>
publicstaticstringToString(TimeSpanvalue)
{
returnToString(value, '');
}
internalstaticstringToString(TimeSpanvalue, charquoteChar)
{
returnToString(value.ToString(), quoteChar);
}
/// <summary>
/// Converts the <seecref='Uri'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Uri'/>.</returns>
publicstaticstringToString(Uri? value)
{
if (valuenull)
{
returnNull;
}
returnToString(value, '');
}
internalstaticstringToString(Urivalue, charquoteChar)
{
returnToString(value.OriginalString, quoteChar);
}
/// <summary>
/// Converts the <seecref='String'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='String'/>.</returns>
publicstaticstringToString(string? value)
{
returnToString(value, '');
}
/// <summary>
/// Converts the <seecref='String'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <paramname='delimiter'>The string delimiter character.</param>
/// <returns>A JSON string representation of the <seecref='String'/>.</returns>
publicstaticstringToString(string? value, chardelimiter)
{
returnToString(value, delimiter, StringEscapeHandling.Default);
}
/// <summary>
/// Converts the <seecref='String'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <paramname='delimiter'>The string delimiter character.</param>
/// <paramname='stringEscapeHandling'>The string escape handling.</param>
/// <returns>A JSON string representation of the <seecref='String'/>.</returns>
publicstaticstringToString(string? value, chardelimiter, StringEscapeHandlingstringEscapeHandling)
{
if (delimiter!=''&&delimiter!=''')
{
thrownewArgumentException('Delimiter must be a single or double quote.', nameof(delimiter));
}
returnJavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, true, stringEscapeHandling);
}
/// <summary>
/// Converts the <seecref='Object'/> to its JSON string representation.
/// </summary>
/// <paramname='value'>The value to convert.</param>
/// <returns>A JSON string representation of the <seecref='Object'/>.</returns>
publicstaticstringToString(object? value)
{
if (valuenull)
{
returnNull;
}
PrimitiveTypeCodetypeCode=ConvertUtils.GetTypeCode(value.GetType());
switch (typeCode)
{
casePrimitiveTypeCode.String:
returnToString((string)value);
casePrimitiveTypeCode.Char:
returnToString((char)value);
casePrimitiveTypeCode.Boolean:
returnToString((bool)value);
casePrimitiveTypeCode.SByte:
returnToString((sbyte)value);
casePrimitiveTypeCode.Int16:
returnToString((short)value);
casePrimitiveTypeCode.UInt16:
returnToString((ushort)value);
casePrimitiveTypeCode.Int32:
returnToString((int)value);
casePrimitiveTypeCode.Byte:
returnToString((byte)value);
casePrimitiveTypeCode.UInt32:
returnToString((uint)value);
casePrimitiveTypeCode.Int64:
returnToString((long)value);
casePrimitiveTypeCode.UInt64:
returnToString((ulong)value);
casePrimitiveTypeCode.Single:
returnToString((float)value);
casePrimitiveTypeCode.Double:
returnToString((double)value);
casePrimitiveTypeCode.DateTime:
returnToString((DateTime)value);
casePrimitiveTypeCode.Decimal:
returnToString((decimal)value);
#ifHAVE_DB_NULL_TYPE_CODE
casePrimitiveTypeCode.DBNull:
returnNull;
#endif
#ifHAVE_DATE_TIME_OFFSET
casePrimitiveTypeCode.DateTimeOffset:
returnToString((DateTimeOffset)value);
#endif
casePrimitiveTypeCode.Guid:
returnToString((Guid)value);
casePrimitiveTypeCode.Uri:
returnToString((Uri)value);
casePrimitiveTypeCode.TimeSpan:
returnToString((TimeSpan)value);
#ifHAVE_BIG_INTEGER
casePrimitiveTypeCode.BigInteger:
returnToStringInternal((BigInteger)value);
#endif
}
thrownewArgumentException('Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.'.FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#regionSerialize
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <paramname='value'>The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
publicstaticstringSerializeObject(object? value)
{
returnSerializeObject(value, null, (JsonSerializerSettings?)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting.
/// </summary>
/// <paramname='value'>The object to serialize.</param>
/// <paramname='formatting'>Indicates how the output should be formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
publicstaticstringSerializeObject(object? value, Formattingformatting)
{
returnSerializeObject(value, formatting, (JsonSerializerSettings?)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <seecref='JsonConverter'/>.
/// </summary>
/// <paramname='value'>The object to serialize.</param>
/// <paramname='converters'>A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
publicstaticstringSerializeObject(object? value, paramsJsonConverter[] converters)
{
JsonSerializerSettings? settings= (converters!=null&&converters.Length>0)
?newJsonSerializerSettings { Converters=converters }
:null;
returnSerializeObject(value, null, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and a collection of <seecref='JsonConverter'/>.
/// </summary>
/// <paramname='value'>The object to serialize.</param>
/// <paramname='formatting'>Indicates how the output should be formatted.</param>
/// <paramname='converters'>A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
publicstaticstringSerializeObject(object? value, Formattingformatting, paramsJsonConverter[] converters)
{
JsonSerializerSettings? settings= (converters!=null&&converters.Length>0)
?newJsonSerializerSettings { Converters=converters }
:null;
returnSerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using <seecref='JsonSerializerSettings'/>.
/// </summary>
/// <paramname='value'>The object to serialize.</param>
/// <paramname='settings'>The <seecref='JsonSerializerSettings'/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
publicstaticstringSerializeObject(object? value, JsonSerializerSettingssettings)
{
returnSerializeObject(value, null, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <seecref='JsonSerializerSettings'/>.
/// </summary>
/// <paramname='value'>The object to serialize.</param>
/// <paramname='settings'>The <seecref='JsonSerializerSettings'/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <paramname='type'>
/// The type of the value being serialized.
/// This parameter is used when <seecref='JsonSerializer.TypeNameHandling'/> is <seecref='TypeNameHandling.Auto'/> to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
publicstaticstringSerializeObject(object? value, Type? type, JsonSerializerSettings? settings)
{
JsonSerializerjsonSerializer=JsonSerializer.CreateDefault(settings);
returnSerializeObjectInternal(value, type, jsonSerializer);
}
/// <summary>
/// Serializes the specified object to a JSON string using formatting and <seecref='JsonSerializerSettings'/>.
/// </summary>
/// <paramname='value'>The object to serialize.</param>
/// <paramname='formatting'>Indicates how the output should be formatted.</param>
/// <paramname='settings'>The <seecref='JsonSerializerSettings'/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
publicstaticstringSerializeObject(object? value, Formattingformatting, JsonSerializerSettings? settings)
{
returnSerializeObject(value, null, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a type, formatting and <seecref='JsonSerializerSettings'/>.
/// </summary>
/// <paramname='value'>The object to serialize.</param>
/// <paramname='formatting'>Indicates how the output should be formatted.</param>
/// <paramname='settings'>The <seecref='JsonSerializerSettings'/> used to serialize the object.
/// If this is <c>null</c>, default serialization settings will be used.</param>
/// <paramname='type'>
/// The type of the value being serialized.
/// This parameter is used when <seecref='JsonSerializer.TypeNameHandling'/> is <seecref='TypeNameHandling.Auto'/> to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
publicstaticstringSerializeObject(object? value, Type? type, Formattingformatting, JsonSerializerSettings? settings)
{
JsonSerializerjsonSerializer=JsonSerializer.CreateDefault(settings);
jsonSerializer.Formatting=formatting;
returnSerializeObjectInternal(value, type, jsonSerializer);
}
privatestaticstringSerializeObjectInternal(object? value, Type? type, JsonSerializerjsonSerializer)
{
StringBuildersb=newStringBuilder(256);
StringWritersw=newStringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriterjsonWriter=newJsonTextWriter(sw))
{
jsonWriter.Formatting=jsonSerializer.Formatting;
jsonSerializer.Serialize(jsonWriter, value, type);
}
returnsw.ToString();
}
#endregion
#regionDeserialize
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <paramname='value'>The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
publicstaticobject? DeserializeObject(stringvalue)
{
returnDeserializeObject(value, null, (JsonSerializerSettings?)null);
}
/// <summary>
/// Deserializes the JSON to a .NET object using <seecref='JsonSerializerSettings'/>.
/// </summary>
/// <paramname='value'>The JSON to deserialize.</param>
/// <paramname='settings'>
/// The <seecref='JsonSerializerSettings'/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
publicstaticobject? DeserializeObject(stringvalue, JsonSerializerSettingssettings)
{
returnDeserializeObject(value, null, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <paramname='value'>The JSON to deserialize.</param>
/// <paramname='type'>The <seecref='Type'/> of object being deserialized.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
publicstaticobject? DeserializeObject(stringvalue, Typetype)
{
returnDeserializeObject(value, type, (JsonSerializerSettings?)null);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparamname='T'>The type of the object to deserialize to.</typeparam>
/// <paramname='value'>The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
publicstaticTDeserializeObject<T>(stringvalue)
{
returnDeserializeObject<T>(value, (JsonSerializerSettings?)null);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type.
/// </summary>
/// <typeparamname='T'>
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be inferred from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <paramname='value'>The JSON to deserialize.</param>
/// <paramname='anonymousTypeObject'>The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
[DebuggerStepThrough]
publicstaticTDeserializeAnonymousType<T>(stringvalue, TanonymousTypeObject)
{
returnDeserializeObject<T>(value);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type using <seecref='JsonSerializerSettings'/>.
/// </summary>
/// <typeparamname='T'>
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be inferred from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <paramname='value'>The JSON to deserialize.</param>
/// <paramname='anonymousTypeObject'>The anonymous type object.</param>
/// <paramname='settings'>
/// The <seecref='JsonSerializerSettings'/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
[DebuggerStepThrough]
publicstaticTDeserializeAnonymousType<T>(stringvalue, TanonymousTypeObject, JsonSerializerSettingssettings)
{
returnDeserializeObject<T>(value, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <seecref='JsonConverter'/>.
/// </summary>
/// <typeparamname='T'>The type of the object to deserialize to.</typeparam>
/// <paramname='value'>The JSON to deserialize.</param>
/// <paramname='converters'>Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
[return: MaybeNull]
publicstaticTDeserializeObject<T>(stringvalue, paramsJsonConverter[] converters)
{
#pragmawarningdisable CS8601 // Possible null reference assignment.
return (T)DeserializeObject(value, typeof(T), converters);
#pragmawarningrestore CS8601 // Possible null reference assignment.
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <seecref='JsonSerializerSettings'/>.
/// </summary>
/// <typeparamname='T'>The type of the object to deserialize to.</typeparam>
/// <paramname='value'>The object to deserialize.</param>
/// <paramname='settings'>
/// The <seecref='JsonSerializerSettings'/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
[return: MaybeNull]
publicstaticTDeserializeObject<T>(stringvalue, JsonSerializerSettings? settings)
{
#pragmawarningdisable CS8601 // Possible null reference assignment.
return (T)DeserializeObject(value, typeof(T), settings);
#pragmawarningrestore CS8601 // Possible null reference assignment.
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using a collection of <seecref='JsonConverter'/>.
/// </summary>
/// <paramname='value'>The JSON to deserialize.</param>
/// <paramname='type'>The type of the object to deserialize.</param>
/// <paramname='converters'>Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
publicstaticobject? DeserializeObject(stringvalue, Typetype, paramsJsonConverter[] converters)
{
JsonSerializerSettings? settings= (converters!=null&&converters.Length>0)
?newJsonSerializerSettings { Converters=converters }
:null;
returnDeserializeObject(value, type, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type using <seecref='JsonSerializerSettings'/>.
/// </summary>
/// <paramname='value'>The JSON to deserialize.</param>
/// <paramname='type'>The type of the object to deserialize to.</param>
/// <paramname='settings'>
/// The <seecref='JsonSerializerSettings'/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
publicstaticobject? DeserializeObject(stringvalue, Type? type, JsonSerializerSettings? settings)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
JsonSerializerjsonSerializer=JsonSerializer.CreateDefault(settings);
// by default DeserializeObject should check for additional content
if (!jsonSerializer.IsCheckAdditionalContentSet())
{
jsonSerializer.CheckAdditionalContent=true;
}
using (JsonTextReaderreader=newJsonTextReader(newStringReader(value)))
{
returnjsonSerializer.Deserialize(reader, type);
}
}
#endregion
#regionPopulate
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <paramname='value'>The JSON to populate values from.</param>
/// <paramname='target'>The target object to populate values onto.</param>
[DebuggerStepThrough]
publicstaticvoidPopulateObject(stringvalue, objecttarget)
{
PopulateObject(value, target, null);
}
/// <summary>
/// Populates the object with values from the JSON string using <seecref='JsonSerializerSettings'/>.
/// </summary>
/// <paramname='value'>The JSON to populate values from.</param>
/// <paramname='target'>The target object to populate values onto.</param>
/// <paramname='settings'>
/// The <seecref='JsonSerializerSettings'/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
publicstaticvoidPopulateObject(stringvalue, objecttarget, JsonSerializerSettings? settings)
{
JsonSerializerjsonSerializer=JsonSerializer.CreateDefault(settings);
using (JsonReaderjsonReader=newJsonTextReader(newStringReader(value)))
{
jsonSerializer.Populate(jsonReader, target);
if (settings!=null&&settings.CheckAdditionalContent)
{
while (jsonReader.Read())
{
if (jsonReader.TokenType!=JsonToken.Comment)
{
throwJsonSerializationException.Create(jsonReader, 'Additional text found in JSON string after finishing deserializing object.');
}
}
}
}
}
#endregion
#regionXml
#ifHAVE_XML_DOCUMENT
/// <summary>
/// Serializes the <seecref='XmlNode'/> to a JSON string.
/// </summary>
/// <paramname='node'>The node to serialize.</param>
/// <returns>A JSON string of the <seecref='XmlNode'/>.</returns>
publicstaticstringSerializeXmlNode(XmlNode? node)
{
returnSerializeXmlNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <seecref='XmlNode'/> to a JSON string using formatting.
/// </summary>
/// <paramname='node'>The node to serialize.</param>
/// <paramname='formatting'>Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <seecref='XmlNode'/>.</returns>
publicstaticstringSerializeXmlNode(XmlNode? node, Formattingformatting)
{
XmlNodeConverterconverter=newXmlNodeConverter();
returnSerializeObject(node, formatting, converter);
}
/// <summary>
/// Serializes the <seecref='XmlNode'/> to a JSON string using formatting and omits the root object if <paramrefname='omitRootObject'/> is <c>true</c>.
/// </summary>
/// <paramname='node'>The node to serialize.</param>
/// <paramname='formatting'>Indicates how the output should be formatted.</param>
/// <paramname='omitRootObject'>Omits writing the root object.</param>
/// <returns>A JSON string of the <seecref='XmlNode'/>.</returns>
publicstaticstringSerializeXmlNode(XmlNode? node, Formattingformatting, boolomitRootObject)
{
XmlNodeConverterconverter=newXmlNodeConverter { OmitRootObject=omitRootObject };
returnSerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <seecref='XmlNode'/> from a JSON string.
/// </summary>
/// <paramname='value'>The JSON string.</param>
/// <returns>The deserialized <seecref='XmlNode'/>.</returns>
publicstaticXmlDocument? DeserializeXmlNode(stringvalue)
{
returnDeserializeXmlNode(value, null);
}
/// <summary>
/// Deserializes the <seecref='XmlNode'/> from a JSON string nested in a root element specified by <paramrefname='deserializeRootElementName'/>.
/// </summary>
/// <paramname='value'>The JSON string.</param>
/// <paramname='deserializeRootElementName'>The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <seecref='XmlNode'/>.</returns>
publicstaticXmlDocument? DeserializeXmlNode(stringvalue, string? deserializeRootElementName)
{
returnDeserializeXmlNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <seecref='XmlNode'/> from a JSON string nested in a root element specified by <paramrefname='deserializeRootElementName'/>
/// and writes a Json.NET array attribute for collections.
/// </summary>
/// <paramname='value'>The JSON string.</param>
/// <paramname='deserializeRootElementName'>The name of the root element to append when deserializing.</param>
/// <paramname='writeArrayAttribute'>
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized <seecref='XmlNode'/>.</returns>
publicstaticXmlDocument? DeserializeXmlNode(stringvalue, string? deserializeRootElementName, boolwriteArrayAttribute)
{
returnDeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
/// <summary>
/// Deserializes the <seecref='XmlNode'/> from a JSON string nested in a root element specified by <paramrefname='deserializeRootElementName'/>,
/// writes a Json.NET array attribute for collections, and encodes special characters.
/// </summary>
/// <paramname='value'>The JSON string.</param>
/// <paramname='deserializeRootElementName'>The name of the root element to append when deserializing.</param>
/// <paramname='writeArrayAttribute'>
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <paramname='encodeSpecialCharacters'>
/// A value to indicate whether to encode special characters when converting JSON to XML.
/// If <c>true</c>, special characters like ':', '@', '?', '#' and '$' in JSON property names aren't used to specify
/// XML namespaces, attributes or processing directives. Instead special characters are encoded and written
/// as part of the XML element name.
/// </param>
/// <returns>The deserialized <seecref='XmlNode'/>.</returns>
publicstaticXmlDocument? DeserializeXmlNode(stringvalue, string? deserializeRootElementName, boolwriteArrayAttribute, boolencodeSpecialCharacters)
{
XmlNodeConverterconverter=newXmlNodeConverter();
converter.DeserializeRootElementName=deserializeRootElementName;
converter.WriteArrayAttribute=writeArrayAttribute;
converter.EncodeSpecialCharacters=encodeSpecialCharacters;
return (XmlDocument?)DeserializeObject(value, typeof(XmlDocument), converter);
}
#endif
#ifHAVE_XLINQ
/// <summary>
/// Serializes the <seecref='XNode'/> to a JSON string.
/// </summary>
/// <paramname='node'>The node to convert to JSON.</param>
/// <returns>A JSON string of the <seecref='XNode'/>.</returns>
publicstaticstringSerializeXNode(XObject? node)
{
returnSerializeXNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <seecref='XNode'/> to a JSON string using formatting.
/// </summary>
/// <paramname='node'>The node to convert to JSON.</param>
/// <paramname='formatting'>Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <seecref='XNode'/>.</returns>
publicstaticstringSerializeXNode(XObject? node, Formattingformatting)
{
returnSerializeXNode(node, formatting, false);
}
/// <summary>
/// Serializes the <seecref='XNode'/> to a JSON string using formatting and omits the root object if <paramrefname='omitRootObject'/> is <c>true</c>.
/// </summary>
/// <paramname='node'>The node to serialize.</param>
/// <paramname='formatting'>Indicates how the output should be formatted.</param>
/// <paramname='omitRootObject'>Omits writing the root object.</param>
/// <returns>A JSON string of the <seecref='XNode'/>.</returns>
publicstaticstringSerializeXNode(XObject? node, Formattingformatting, boolomitRootObject)
{
XmlNodeConverterconverter=newXmlNodeConverter { OmitRootObject=omitRootObject };
returnSerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <seecref='XNode'/> from a JSON string.
/// </summary>
/// <paramname='value'>The JSON string.</param>
/// <returns>The deserialized <seecref='XNode'/>.</returns>
publicstaticXDocument? DeserializeXNode(stringvalue)
{
returnDeserializeXNode(value, null);
}
/// <summary>
/// Deserializes the <seecref='XNode'/> from a JSON string nested in a root element specified by <paramrefname='deserializeRootElementName'/>.
/// </summary>
/// <paramname='value'>The JSON string.</param>
/// <paramname='deserializeRootElementName'>The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <seecref='XNode'/>.</returns>
publicstaticXDocument? DeserializeXNode(stringvalue, string? deserializeRootElementName)
{
returnDeserializeXNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <seecref='XNode'/> from a JSON string nested in a root element specified by <paramrefname='deserializeRootElementName'/>
/// and writes a Json.NET array attribute for collections.
/// </summary>
/// <paramname='value'>The JSON string.</param>
/// <paramname='deserializeRootElementName'>The name of the root element to append when deserializing.</param>
/// <paramname='writeArrayAttribute'>
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized <seecref='XNode'/>.</returns>
publicstaticXDocument? DeserializeXNode(stringvalue, string? deserializeRootElementName, boolwriteArrayAttribute)
{
returnDeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
/// <summary>
/// Deserializes the <seecref='XNode'/> from a JSON string nested in a root element specified by <paramrefname='deserializeRootElementName'/>,
/// writes a Json.NET array attribute for collections, and encodes special characters.
/// </summary>
/// <paramname='value'>The JSON string.</param>
/// <paramname='deserializeRootElementName'>The name of the root element to append when deserializing.</param>
/// <paramname='writeArrayAttribute'>
/// A value to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <paramname='encodeSpecialCharacters'>
/// A value to indicate whether to encode special characters when converting JSON to XML.
/// If <c>true</c>, special characters like ':', '@', '?', '#' and '$' in JSON property names aren't used to specify
/// XML namespaces, attributes or processing directives. Instead special characters are encoded and written
/// as part of the XML element name.
/// </param>
/// <returns>The deserialized <seecref='XNode'/>.</returns>
publicstaticXDocument? DeserializeXNode(stringvalue, string? deserializeRootElementName, boolwriteArrayAttribute, boolencodeSpecialCharacters)
{
XmlNodeConverterconverter=newXmlNodeConverter();
converter.DeserializeRootElementName=deserializeRootElementName;
converter.WriteArrayAttribute=writeArrayAttribute;
converter.EncodeSpecialCharacters=encodeSpecialCharacters;
return (XDocument?)DeserializeObject(value, typeof(XDocument), converter);
}
#endif
#endregion
}
}
  • Copy lines
  • Copy permalink
-->

JSON (JavaScript Object Notation) is an efficient data encoding format that enables fast exchanges of small amounts of data between client browsers and AJAX-enabled Web services.

This article demonstrates how to serialize .NET type objects into JSON-encoded data and then deserialize data in the JSON format back into instances of .NET types. This example uses a data contract to demonstrate serialization and deserialization of a user-defined Person type and uses DataContractJsonSerializer.

Normally, JSON serialization and deserialization are handled automatically by Windows Communication Foundation (WCF) when you use data contract types in service operations that are exposed over AJAX-enabled endpoints. However, in some cases you may need to work with JSON data directly.

Note

If an error occurs during serialization of an outgoing reply on the server or for some other reason, it may not get returned to the client as a fault.

Newtonsoft Json Deserialize Null

This article is based on the JSON serialization sample.

To define the data contract for a Person type

  1. Define the data contract for Person by attaching the DataContractAttribute to the class and DataMemberAttribute attribute to the members you want to serialize. For more information about data contracts, see Designing service contracts.

To serialize an instance of type Person to JSON

  1. Create an instance of the Person type.

  2. Serialize the Person object to a memory stream by using the DataContractJsonSerializer.

  3. Use the WriteObject method to write JSON data to the stream.

  4. Show the JSON output.

To deserialize an instance of type Person from JSON

  1. Deserialize the JSON-encoded data into a new instance of Person by using the ReadObject method of the DataContractJsonSerializer.

  2. Show the results.

Newtonsoft Json Deserialize Datetime

Example

Newtonsoft Json Deserialize Stream

Note

The JSON serializer throws a serialization exception for data contracts that have multiple members with the same name, as shown in the following sample code.

Newtonsoft Json Deserialize List

See also