Newtonsoft Json Serializer

Newtonsoft Json Serializer

  1. Newtonsoft Json Serializer Performance
  2. Newtonsoft Json Serializer Depth
  3. Newtonsoft.json.dll

Here we will learn how to use newtonsoft JSON to serialize and deserialize in asp.net using c#, vb.net with example or Use newtonsoft.json for JSON serialization and deserialization in asp.net using c#, vb.net with example or serializing / deserializing JSON data in asp.net using c#, vb.net with example. Microsoft.AspNetCore.Mvc depends on Microsoft.AspNetCore.Formatter.Json which depends on Microsoft.AspNetCore.JsonPatch, which depends on Newtonsoft.Json (see source). This is only true for ASP.NET Core 1.0 to 2.2. ASP.NET Core 3.0 removes the dependency on JSON.NET and uses it's own JSON serializer.

Permalink

Join GitHub today

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

Sign up

Newtonsoft Json Serializer Performance

Find file Copy path
JamesNKFix allocating empty arrays and more nullable warningsd75074fAug 18, 2019
6 contributors

Newtonsoft Json Serializer Depth

#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.Collections;
usingSystem.Collections.Generic;
usingSystem.Diagnostics;
usingSystem.Globalization;
usingSystem.IO;
usingSystem.Runtime.Serialization.Formatters;
usingNewtonsoft.Json.Converters;
usingNewtonsoft.Json.Serialization;
usingNewtonsoft.Json.Utilities;
usingSystem.Runtime.Serialization;
usingErrorEventArgs=Newtonsoft.Json.Serialization.ErrorEventArgs;
usingSystem.Runtime.CompilerServices;
usingSystem.Diagnostics.CodeAnalysis;
namespaceNewtonsoft.Json
{
/// <summary>
/// Serializes and deserializes objects into and from the JSON format.
/// The <seecref='JsonSerializer'/> enables you to control how objects are encoded into JSON.
/// </summary>
publicclassJsonSerializer
{
internalTypeNameHandling_typeNameHandling;
internalTypeNameAssemblyFormatHandling_typeNameAssemblyFormatHandling;
internalPreserveReferencesHandling_preserveReferencesHandling;
internalReferenceLoopHandling_referenceLoopHandling;
internalMissingMemberHandling_missingMemberHandling;
internalObjectCreationHandling_objectCreationHandling;
internalNullValueHandling_nullValueHandling;
internalDefaultValueHandling_defaultValueHandling;
internalConstructorHandling_constructorHandling;
internalMetadataPropertyHandling_metadataPropertyHandling;
internalJsonConverterCollection? _converters;
internalIContractResolver_contractResolver;
internalITraceWriter? _traceWriter;
internalIEqualityComparer? _equalityComparer;
internalISerializationBinder_serializationBinder;
internalStreamingContext_context;
privateIReferenceResolver? _referenceResolver;
privateFormatting? _formatting;
privateDateFormatHandling? _dateFormatHandling;
privateDateTimeZoneHandling? _dateTimeZoneHandling;
privateDateParseHandling? _dateParseHandling;
privateFloatFormatHandling? _floatFormatHandling;
privateFloatParseHandling? _floatParseHandling;
privateStringEscapeHandling? _stringEscapeHandling;
privateCultureInfo_culture;
privateint? _maxDepth;
privatebool_maxDepthSet;
privatebool? _checkAdditionalContent;
privatestring? _dateFormatString;
privatebool_dateFormatStringSet;
/// <summary>
/// Occurs when the <seecref='JsonSerializer'/> errors during serialization and deserialization.
/// </summary>
publicvirtualeventEventHandler<ErrorEventArgs>? Error;
/// <summary>
/// Gets or sets the <seecref='IReferenceResolver'/> used by the serializer when resolving references.
/// </summary>
publicvirtualIReferenceResolver? ReferenceResolver
{
get=>GetReferenceResolver();
set
{
if (valuenull)
{
thrownewArgumentNullException(nameof(value), 'Reference resolver cannot be null.');
}
_referenceResolver=value;
}
}
/// <summary>
/// Gets or sets the <seecref='SerializationBinder'/> used by the serializer when resolving type names.
/// </summary>
[Obsolete('Binder is obsolete. Use SerializationBinder instead.')]
publicvirtualSerializationBinderBinder
{
get
{
if (_serializationBinderisSerializationBinderlegacySerializationBinder)
{
returnlegacySerializationBinder;
}
if (_serializationBinderisSerializationBinderAdapteradapter)
{
returnadapter.SerializationBinder;
}
thrownewInvalidOperationException('Cannot get SerializationBinder because an ISerializationBinder was previously set.');
}
set
{
if (valuenull)
{
thrownewArgumentNullException(nameof(value), 'Serialization binder cannot be null.');
}
_serializationBinder=valueasISerializationBinder ?? newSerializationBinderAdapter(value);
}
}
/// <summary>
/// Gets or sets the <seecref='ISerializationBinder'/> used by the serializer when resolving type names.
/// </summary>
publicvirtualISerializationBinderSerializationBinder
{
get=>_serializationBinder;
set
{
if (valuenull)
{
thrownewArgumentNullException(nameof(value), 'Serialization binder cannot be null.');
}
_serializationBinder=value;
}
}
/// <summary>
/// Gets or sets the <seecref='ITraceWriter'/> used by the serializer when writing trace messages.
/// </summary>
/// <value>The trace writer.</value>
publicvirtualITraceWriter? TraceWriter
{
get=>_traceWriter;
set=>_traceWriter=value;
}
/// <summary>
/// Gets or sets the equality comparer used by the serializer when comparing references.
/// </summary>
/// <value>The equality comparer.</value>
publicvirtualIEqualityComparer? EqualityComparer
{
get=>_equalityComparer;
set=>_equalityComparer=value;
}
/// <summary>
/// Gets or sets how type name writing and reading is handled by the serializer.
/// The default value is <seecref='Json.TypeNameHandling.None' />.
/// </summary>
/// <remarks>
/// <seecref='JsonSerializer.TypeNameHandling'/> should be used with caution when your application deserializes JSON from an external source.
/// Incoming types should be validated with a custom <seecref='JsonSerializer.SerializationBinder'/>
/// when deserializing with a value other than <seecref='TypeNameHandling.None'/>.
/// </remarks>
publicvirtualTypeNameHandlingTypeNameHandling
{
get=>_typeNameHandling;
set
{
if (value<TypeNameHandling.None||value>TypeNameHandling.Auto)
{
thrownewArgumentOutOfRangeException(nameof(value));
}
_typeNameHandling=value;
}
}
/// <summary>
/// Gets or sets how a type name assembly is written and resolved by the serializer.
/// The default value is <seecref='FormatterAssemblyStyle.Simple' />.
/// </summary>
/// <value>The type name assembly format.</value>
[Obsolete('TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.')]
publicvirtualFormatterAssemblyStyleTypeNameAssemblyFormat
{
get=> (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling;
set
{
if (value<FormatterAssemblyStyle.Simple||value>FormatterAssemblyStyle.Full)
{
thrownewArgumentOutOfRangeException(nameof(value));
}
_typeNameAssemblyFormatHandling= (TypeNameAssemblyFormatHandling)value;
}
}
/// <summary>
/// Gets or sets how a type name assembly is written and resolved by the serializer.
/// The default value is <seecref='Json.TypeNameAssemblyFormatHandling.Simple' />.
/// </summary>
/// <value>The type name assembly format.</value>
publicvirtualTypeNameAssemblyFormatHandlingTypeNameAssemblyFormatHandling
{
get=>_typeNameAssemblyFormatHandling;
set
{
if (value<TypeNameAssemblyFormatHandling.Simple||value>TypeNameAssemblyFormatHandling.Full)
{
thrownewArgumentOutOfRangeException(nameof(value));
}
_typeNameAssemblyFormatHandling=value;
}
}
/// <summary>
/// Gets or sets how object references are preserved by the serializer.
/// The default value is <seecref='Json.PreserveReferencesHandling.None' />.
/// </summary>
publicvirtualPreserveReferencesHandlingPreserveReferencesHandling
{
get=>_preserveReferencesHandling;
set
{
if (value<PreserveReferencesHandling.None||value>PreserveReferencesHandling.All)
{
thrownewArgumentOutOfRangeException(nameof(value));
}
_preserveReferencesHandling=value;
}
}
/// <summary>
/// Gets or sets how reference loops (e.g. a class referencing itself) is handled.
/// The default value is <seecref='Json.ReferenceLoopHandling.Error' />.
/// </summary>
publicvirtualReferenceLoopHandlingReferenceLoopHandling
{
get=>_referenceLoopHandling;
set
{
if (value<ReferenceLoopHandling.Error||value>ReferenceLoopHandling.Serialize)
{
thrownewArgumentOutOfRangeException(nameof(value));
}
_referenceLoopHandling=value;
}
}
/// <summary>
/// Gets or sets how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization.
/// The default value is <seecref='Json.MissingMemberHandling.Ignore' />.
/// </summary>
publicvirtualMissingMemberHandlingMissingMemberHandling
{
get=>_missingMemberHandling;
set
{
if (value<MissingMemberHandling.Ignore||value>MissingMemberHandling.Error)
{
thrownewArgumentOutOfRangeException(nameof(value));
}
_missingMemberHandling=value;
}
}
/// <summary>
/// Gets or sets how null values are handled during serialization and deserialization.
/// The default value is <seecref='Json.NullValueHandling.Include' />.
/// </summary>
publicvirtualNullValueHandlingNullValueHandling
{
get=>_nullValueHandling;
set
{
if (value<NullValueHandling.Include||value>NullValueHandling.Ignore)
{
thrownewArgumentOutOfRangeException(nameof(value));
}
_nullValueHandling=value;
}
}
/// <summary>
/// Gets or sets how default values are handled during serialization and deserialization.
/// The default value is <seecref='Json.DefaultValueHandling.Include' />.
/// </summary>
publicvirtualDefaultValueHandlingDefaultValueHandling
{
get=>_defaultValueHandling;
set
{
if (value<DefaultValueHandling.Include||value>DefaultValueHandling.IgnoreAndPopulate)
{
thrownewArgumentOutOfRangeException(nameof(value));
}
_defaultValueHandling=value;
}
}
/// <summary>
/// Gets or sets how objects are created during deserialization.
/// The default value is <seecref='Json.ObjectCreationHandling.Auto' />.
/// </summary>
/// <value>The object creation handling.</value>
publicvirtualObjectCreationHandlingObjectCreationHandling
{
get=>_objectCreationHandling;
set
{
if (value<ObjectCreationHandling.Auto||value>ObjectCreationHandling.Replace)
{
thrownewArgumentOutOfRangeException(nameof(value));
}
_objectCreationHandling=value;
}
}
/// <summary>
/// Gets or sets how constructors are used during deserialization.
/// The default value is <seecref='Json.ConstructorHandling.Default' />.
/// </summary>
/// <value>The constructor handling.</value>
publicvirtualConstructorHandlingConstructorHandling
{
get=>_constructorHandling;
set
{
if (value<ConstructorHandling.Default||value>ConstructorHandling.AllowNonPublicDefaultConstructor)
{
thrownewArgumentOutOfRangeException(nameof(value));
}
_constructorHandling=value;
}
}
/// <summary>
/// Gets or sets how metadata properties are used during deserialization.
/// The default value is <seecref='Json.MetadataPropertyHandling.Default' />.
/// </summary>
/// <value>The metadata properties handling.</value>
publicvirtualMetadataPropertyHandlingMetadataPropertyHandling
{
get=>_metadataPropertyHandling;
set
{
if (value<MetadataPropertyHandling.Default||value>MetadataPropertyHandling.Ignore)
{
thrownewArgumentOutOfRangeException(nameof(value));
}
_metadataPropertyHandling=value;
}
}
/// <summary>
/// Gets a collection <seecref='JsonConverter'/> that will be used during serialization.
/// </summary>
/// <value>Collection <seecref='JsonConverter'/> that will be used during serialization.</value>
publicvirtualJsonConverterCollectionConverters
{
get
{
if (_convertersnull)
{
_converters=newJsonConverterCollection();
}
return_converters;
}
}
/// <summary>
/// Gets or sets the contract resolver used by the serializer when
/// serializing .NET objects to JSON and vice versa.
/// </summary>
publicvirtualIContractResolverContractResolver
{
get=>_contractResolver;
set=>_contractResolver=value??DefaultContractResolver.Instance;
}
/// <summary>
/// Gets or sets the <seecref='StreamingContext'/> used by the serializer when invoking serialization callback methods.
/// </summary>
/// <value>The context.</value>
publicvirtualStreamingContextContext
{
get=>_context;
set=>_context=value;
}
/// <summary>
/// Indicates how JSON text output is formatted.
/// The default value is <seecref='Json.Formatting.None' />.
/// </summary>
publicvirtualFormattingFormatting
{
get=>_formatting??JsonSerializerSettings.DefaultFormatting;
set=>_formatting=value;
}
/// <summary>
/// Gets or sets how dates are written to JSON text.
/// The default value is <seecref='Json.DateFormatHandling.IsoDateFormat' />.
/// </summary>
publicvirtualDateFormatHandlingDateFormatHandling
{
get=>_dateFormatHandling??JsonSerializerSettings.DefaultDateFormatHandling;
set=>_dateFormatHandling=value;
}
/// <summary>
/// Gets or sets how <seecref='DateTime'/> time zones are handled during serialization and deserialization.
/// The default value is <seecref='Json.DateTimeZoneHandling.RoundtripKind' />.
/// </summary>
publicvirtualDateTimeZoneHandlingDateTimeZoneHandling
{
get=>_dateTimeZoneHandling??JsonSerializerSettings.DefaultDateTimeZoneHandling;
set=>_dateTimeZoneHandling=value;
}
/// <summary>
/// Gets or sets how date formatted strings, e.g. <c>'/Date(1198908717056)/'</c> and <c>'2012-03-21T05:40Z'</c>, are parsed when reading JSON.
/// The default value is <seecref='Json.DateParseHandling.DateTime' />.
/// </summary>
publicvirtualDateParseHandlingDateParseHandling
{
get=>_dateParseHandling??JsonSerializerSettings.DefaultDateParseHandling;
set=>_dateParseHandling=value;
}
/// <summary>
/// Gets or sets how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// The default value is <seecref='Json.FloatParseHandling.Double' />.
/// </summary>
publicvirtualFloatParseHandlingFloatParseHandling
{
get=>_floatParseHandling??JsonSerializerSettings.DefaultFloatParseHandling;
set=>_floatParseHandling=value;
}
/// <summary>
/// Gets or sets how special floating point numbers, e.g. <seecref='Double.NaN'/>,
/// <seecref='Double.PositiveInfinity'/> and <seecref='Double.NegativeInfinity'/>,
/// are written as JSON text.
/// The default value is <seecref='Json.FloatFormatHandling.String' />.
/// </summary>
publicvirtualFloatFormatHandlingFloatFormatHandling
{
get=>_floatFormatHandling??JsonSerializerSettings.DefaultFloatFormatHandling;
set=>_floatFormatHandling=value;
}
/// <summary>
/// Gets or sets how strings are escaped when writing JSON text.
/// The default value is <seecref='Json.StringEscapeHandling.Default' />.
/// </summary>
publicvirtualStringEscapeHandlingStringEscapeHandling
{
get=>_stringEscapeHandling??JsonSerializerSettings.DefaultStringEscapeHandling;
set=>_stringEscapeHandling=value;
}
/// <summary>
/// Gets or sets how <seecref='DateTime'/> and <seecref='DateTimeOffset'/> values are formatted when writing JSON text,
/// and the expected date format when reading JSON text.
/// The default value is <c>'yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK'</c>.
/// </summary>
publicvirtualstringDateFormatString
{
get=>_dateFormatString??JsonSerializerSettings.DefaultDateFormatString;
set
{
_dateFormatString=value;
_dateFormatStringSet=true;
}
}
/// <summary>
/// Gets or sets the culture used when reading JSON.
/// The default value is <seecref='CultureInfo.InvariantCulture'/>.
/// </summary>
publicvirtualCultureInfoCulture
{
get=>_culture??JsonSerializerSettings.DefaultCulture;
set=>_culture=value;
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <seecref='JsonReaderException'/>.
/// A null value means there is no maximum.
/// The default value is <c>null</c>.
/// </summary>
publicvirtualint? MaxDepth
{
get=>_maxDepth;
set
{
if (value<=0)
{
thrownewArgumentException('Value must be positive.', nameof(value));
}
_maxDepth=value;
_maxDepthSet=true;
}
}
/// <summary>
/// Gets a value indicating whether there will be a check for additional JSON content after deserializing an object.
/// The default value is <c>false</c>.
/// </summary>
/// <value>
/// <c>true</c> if there will be a check for additional JSON content after deserializing an object; otherwise, <c>false</c>.
/// </value>
publicvirtualboolCheckAdditionalContent
{
get=>_checkAdditionalContent??JsonSerializerSettings.DefaultCheckAdditionalContent;
set=>_checkAdditionalContent=value;
}
internalboolIsCheckAdditionalContentSet()
{
return (_checkAdditionalContent!=null);
}
/// <summary>
/// Initializes a new instance of the <seecref='JsonSerializer'/> class.
/// </summary>
publicJsonSerializer()
{
_referenceLoopHandling=JsonSerializerSettings.DefaultReferenceLoopHandling;
_missingMemberHandling=JsonSerializerSettings.DefaultMissingMemberHandling;
_nullValueHandling=JsonSerializerSettings.DefaultNullValueHandling;
_defaultValueHandling=JsonSerializerSettings.DefaultDefaultValueHandling;
_objectCreationHandling=JsonSerializerSettings.DefaultObjectCreationHandling;
_preserveReferencesHandling=JsonSerializerSettings.DefaultPreserveReferencesHandling;
_constructorHandling=JsonSerializerSettings.DefaultConstructorHandling;
_typeNameHandling=JsonSerializerSettings.DefaultTypeNameHandling;
_metadataPropertyHandling=JsonSerializerSettings.DefaultMetadataPropertyHandling;
_context=JsonSerializerSettings.DefaultContext;
_serializationBinder=DefaultSerializationBinder.Instance;
_culture=JsonSerializerSettings.DefaultCulture;
_contractResolver=DefaultContractResolver.Instance;
}
/// <summary>
/// Creates a new <seecref='JsonSerializer'/> instance.
/// The <seecref='JsonSerializer'/> will not use default settings
/// from <seecref='JsonConvert.DefaultSettings'/>.
/// </summary>
/// <returns>
/// A new <seecref='JsonSerializer'/> instance.
/// The <seecref='JsonSerializer'/> will not use default settings
/// from <seecref='JsonConvert.DefaultSettings'/>.
/// </returns>
publicstaticJsonSerializerCreate()
{
returnnewJsonSerializer();
}
/// <summary>
/// Creates a new <seecref='JsonSerializer'/> instance using the specified <seecref='JsonSerializerSettings'/>.
/// The <seecref='JsonSerializer'/> will not use default settings
/// from <seecref='JsonConvert.DefaultSettings'/>.
/// </summary>
/// <paramname='settings'>The settings to be applied to the <seecref='JsonSerializer'/>.</param>
/// <returns>
/// A new <seecref='JsonSerializer'/> instance using the specified <seecref='JsonSerializerSettings'/>.
/// The <seecref='JsonSerializer'/> will not use default settings
/// from <seecref='JsonConvert.DefaultSettings'/>.
/// </returns>
publicstaticJsonSerializerCreate(JsonSerializerSettings? settings)
{
JsonSerializerserializer=Create();
if (settings!=null)
{
ApplySerializerSettings(serializer, settings);
}
returnserializer;
}
/// <summary>
/// Creates a new <seecref='JsonSerializer'/> instance.
/// The <seecref='JsonSerializer'/> will use default settings
/// from <seecref='JsonConvert.DefaultSettings'/>.
/// </summary>
/// <returns>
/// A new <seecref='JsonSerializer'/> instance.
/// The <seecref='JsonSerializer'/> will use default settings
/// from <seecref='JsonConvert.DefaultSettings'/>.
/// </returns>
publicstaticJsonSerializerCreateDefault()
{
// copy static to local variable to avoid concurrency issues
JsonSerializerSettings? defaultSettings=JsonConvert.DefaultSettings?.Invoke();
returnCreate(defaultSettings);
}
/// <summary>
/// Creates a new <seecref='JsonSerializer'/> instance using the specified <seecref='JsonSerializerSettings'/>.
/// The <seecref='JsonSerializer'/> will use default settings
/// from <seecref='JsonConvert.DefaultSettings'/> as well as the specified <seecref='JsonSerializerSettings'/>.
/// </summary>
/// <paramname='settings'>The settings to be applied to the <seecref='JsonSerializer'/>.</param>
/// <returns>
/// A new <seecref='JsonSerializer'/> instance using the specified <seecref='JsonSerializerSettings'/>.
/// The <seecref='JsonSerializer'/> will use default settings
/// from <seecref='JsonConvert.DefaultSettings'/> as well as the specified <seecref='JsonSerializerSettings'/>.
/// </returns>
publicstaticJsonSerializerCreateDefault(JsonSerializerSettings? settings)
{
JsonSerializerserializer=CreateDefault();
if (settings!=null)
{
ApplySerializerSettings(serializer, settings);
}
returnserializer;
}
privatestaticvoidApplySerializerSettings(JsonSerializerserializer, JsonSerializerSettingssettings)
{
if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
{
// insert settings converters at the beginning so they take precedence
// if user wants to remove one of the default converters they will have to do it manually
for (inti=0; i<settings.Converters.Count; i++)
{
serializer.Converters.Insert(i, settings.Converters[i]);
}
}
// serializer specific
if (settings._typeNameHandling!=null)
{
serializer.TypeNameHandling=settings.TypeNameHandling;
}
if (settings._metadataPropertyHandling!=null)
{
serializer.MetadataPropertyHandling=settings.MetadataPropertyHandling;
}
if (settings._typeNameAssemblyFormatHandling!=null)
{
serializer.TypeNameAssemblyFormatHandling=settings.TypeNameAssemblyFormatHandling;
}
if (settings._preserveReferencesHandling!=null)
{
serializer.PreserveReferencesHandling=settings.PreserveReferencesHandling;
}
if (settings._referenceLoopHandling!=null)
{
serializer.ReferenceLoopHandling=settings.ReferenceLoopHandling;
}
if (settings._missingMemberHandling!=null)
{
serializer.MissingMemberHandling=settings.MissingMemberHandling;
}
if (settings._objectCreationHandling!=null)
{
serializer.ObjectCreationHandling=settings.ObjectCreationHandling;
}
if (settings._nullValueHandling!=null)
{
serializer.NullValueHandling=settings.NullValueHandling;
}
if (settings._defaultValueHandling!=null)
{
serializer.DefaultValueHandling=settings.DefaultValueHandling;
}
if (settings._constructorHandling!=null)
{
serializer.ConstructorHandling=settings.ConstructorHandling;
}
if (settings._context!=null)
{
serializer.Context=settings.Context;
}
if (settings._checkAdditionalContent!=null)
{
serializer._checkAdditionalContent=settings._checkAdditionalContent;
}
if (settings.Error!=null)
{
serializer.Error+=settings.Error;
}
if (settings.ContractResolver!=null)
{
serializer.ContractResolver=settings.ContractResolver;
}
if (settings.ReferenceResolverProvider!=null)
{
serializer.ReferenceResolver=settings.ReferenceResolverProvider();
}
if (settings.TraceWriter!=null)
{
serializer.TraceWriter=settings.TraceWriter;
}
if (settings.EqualityComparer!=null)
{
serializer.EqualityComparer=settings.EqualityComparer;
}
if (settings.SerializationBinder!=null)
{
serializer.SerializationBinder=settings.SerializationBinder;
}
// reader/writer specific
// unset values won't override reader/writer set values
if (settings._formatting!=null)
{
serializer._formatting=settings._formatting;
}
if (settings._dateFormatHandling!=null)
{
serializer._dateFormatHandling=settings._dateFormatHandling;
}
if (settings._dateTimeZoneHandling!=null)
{
serializer._dateTimeZoneHandling=settings._dateTimeZoneHandling;
}
if (settings._dateParseHandling!=null)
{
serializer._dateParseHandling=settings._dateParseHandling;
}
if (settings._dateFormatStringSet)
{
serializer._dateFormatString=settings._dateFormatString;
serializer._dateFormatStringSet=settings._dateFormatStringSet;
}
if (settings._floatFormatHandling!=null)
{
serializer._floatFormatHandling=settings._floatFormatHandling;
}
if (settings._floatParseHandling!=null)
{
serializer._floatParseHandling=settings._floatParseHandling;
}
if (settings._stringEscapeHandling!=null)
{
serializer._stringEscapeHandling=settings._stringEscapeHandling;
}
if (settings._culture!=null)
{
serializer._culture=settings._culture;
}
if (settings._maxDepthSet)
{
serializer._maxDepth=settings._maxDepth;
serializer._maxDepthSet=settings._maxDepthSet;
}
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <paramname='reader'>The <seecref='TextReader'/> that contains the JSON structure to read values from.</param>
/// <paramname='target'>The target object to populate values onto.</param>
[DebuggerStepThrough]
publicvoidPopulate(TextReaderreader, objecttarget)
{
Populate(newJsonTextReader(reader), target);
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <paramname='reader'>The <seecref='JsonReader'/> that contains the JSON structure to read values from.</param>
/// <paramname='target'>The target object to populate values onto.</param>
[DebuggerStepThrough]
publicvoidPopulate(JsonReaderreader, objecttarget)
{
PopulateInternal(reader, target);
}
internalvirtualvoidPopulateInternal(JsonReaderreader, objecttarget)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
ValidationUtils.ArgumentNotNull(target, nameof(target));
SetupReader(
reader,
outCultureInfo? previousCulture,
outDateTimeZoneHandling? previousDateTimeZoneHandling,
outDateParseHandling? previousDateParseHandling,
outFloatParseHandling? previousFloatParseHandling,
outint? previousMaxDepth,
outstring? previousDateFormatString);
TraceJsonReader? traceJsonReader= (TraceWriter!=null&&TraceWriter.LevelFilter>=TraceLevel.Verbose)
?CreateTraceJsonReader(reader)
:null;
JsonSerializerInternalReaderserializerReader=newJsonSerializerInternalReader(this);
serializerReader.Populate(traceJsonReader??reader, target);
if (traceJsonReader!=null)
{
TraceWriter!.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
}
ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
}
/// <summary>
/// Deserializes the JSON structure contained by the specified <seecref='JsonReader'/>.
/// </summary>
/// <paramname='reader'>The <seecref='JsonReader'/> that contains the JSON structure to deserialize.</param>
/// <returns>The <seecref='Object'/> being deserialized.</returns>
[DebuggerStepThrough]
publicobject? Deserialize(JsonReaderreader)
{
returnDeserialize(reader, null);
}
/// <summary>
/// Deserializes the JSON structure contained by the specified <seecref='TextReader'/>
/// into an instance of the specified type.
/// </summary>
/// <paramname='reader'>The <seecref='TextReader'/> containing the object.</param>
/// <paramname='objectType'>The <seecref='Type'/> of object being deserialized.</param>
/// <returns>The instance of <paramrefname='objectType'/> being deserialized.</returns>
[DebuggerStepThrough]
publicobject? Deserialize(TextReaderreader, TypeobjectType)
{
returnDeserialize(newJsonTextReader(reader), objectType);
}
/// <summary>
/// Deserializes the JSON structure contained by the specified <seecref='JsonReader'/>
/// into an instance of the specified type.
/// </summary>
/// <paramname='reader'>The <seecref='JsonReader'/> containing the object.</param>
/// <typeparamname='T'>The type of the object to deserialize.</typeparam>
/// <returns>The instance of <typeparamrefname='T'/> being deserialized.</returns>
[DebuggerStepThrough]
[return: MaybeNull]
publicTDeserialize<T>(JsonReaderreader)
{
#pragmawarningdisable CS8601 // Possible null reference assignment.
return (T)Deserialize(reader, typeof(T));
#pragmawarningrestore CS8601 // Possible null reference assignment.
}
/// <summary>
/// Deserializes the JSON structure contained by the specified <seecref='JsonReader'/>
/// into an instance of the specified type.
/// </summary>
/// <paramname='reader'>The <seecref='JsonReader'/> containing the object.</param>
/// <paramname='objectType'>The <seecref='Type'/> of object being deserialized.</param>
/// <returns>The instance of <paramrefname='objectType'/> being deserialized.</returns>
[DebuggerStepThrough]
publicobject? Deserialize(JsonReaderreader, Type? objectType)
{
returnDeserializeInternal(reader, objectType);
}
internalvirtualobject? DeserializeInternal(JsonReaderreader, Type? objectType)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
SetupReader(
reader,
outCultureInfo? previousCulture,
outDateTimeZoneHandling? previousDateTimeZoneHandling,
outDateParseHandling? previousDateParseHandling,
outFloatParseHandling? previousFloatParseHandling,
outint? previousMaxDepth,
outstring? previousDateFormatString);
TraceJsonReader? traceJsonReader= (TraceWriter!=null&&TraceWriter.LevelFilter>=TraceLevel.Verbose)
?CreateTraceJsonReader(reader)
:null;
JsonSerializerInternalReaderserializerReader=newJsonSerializerInternalReader(this);
object? value=serializerReader.Deserialize(traceJsonReader??reader, objectType, CheckAdditionalContent);
if (traceJsonReader!=null)
{
TraceWriter!.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
}
ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
returnvalue;
}
privatevoidSetupReader(JsonReaderreader, outCultureInfo? previousCulture, outDateTimeZoneHandling? previousDateTimeZoneHandling, outDateParseHandling? previousDateParseHandling, outFloatParseHandling? previousFloatParseHandling, outint? previousMaxDepth, outstring? previousDateFormatString)
{
if (_culture!=null&&!_culture.Equals(reader.Culture))
{
previousCulture=reader.Culture;
reader.Culture=_culture;
}
else
{
previousCulture=null;
}
if (_dateTimeZoneHandling!=null&&reader.DateTimeZoneHandling!=_dateTimeZoneHandling)
{
previousDateTimeZoneHandling=reader.DateTimeZoneHandling;
reader.DateTimeZoneHandling=_dateTimeZoneHandling.GetValueOrDefault();
}
else
{
previousDateTimeZoneHandling=null;
}
if (_dateParseHandling!=null&&reader.DateParseHandling!=_dateParseHandling)
{
previousDateParseHandling=reader.DateParseHandling;
reader.DateParseHandling=_dateParseHandling.GetValueOrDefault();
}
else
{
previousDateParseHandling=null;
}
if (_floatParseHandling!=null&&reader.FloatParseHandling!=_floatParseHandling)
{
previousFloatParseHandling=reader.FloatParseHandling;
reader.FloatParseHandling=_floatParseHandling.GetValueOrDefault();
}
else
{
previousFloatParseHandling=null;
}
if (_maxDepthSet&&reader.MaxDepth!=_maxDepth)
{
previousMaxDepth=reader.MaxDepth;
reader.MaxDepth=_maxDepth;
}
else
{
previousMaxDepth=null;
}
if (_dateFormatStringSet&&reader.DateFormatString!=_dateFormatString)
{
previousDateFormatString=reader.DateFormatString;
reader.DateFormatString=_dateFormatString;
}
else
{
previousDateFormatString=null;
}
if (readerisJsonTextReadertextReader)
{
if (textReader.PropertyNameTablenull&&_contractResolverisDefaultContractResolverresolver)
{
textReader.PropertyNameTable=resolver.GetNameTable();
}
}
}
privatevoidResetReader(JsonReaderreader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString)
{
// reset reader back to previous options
if (previousCulture!=null)
{
reader.Culture=previousCulture;
}
if (previousDateTimeZoneHandling!=null)
{
reader.DateTimeZoneHandling=previousDateTimeZoneHandling.GetValueOrDefault();
}
if (previousDateParseHandling!=null)
{
reader.DateParseHandling=previousDateParseHandling.GetValueOrDefault();
}
if (previousFloatParseHandling!=null)
{
reader.FloatParseHandling=previousFloatParseHandling.GetValueOrDefault();
}
if (_maxDepthSet)
{
reader.MaxDepth=previousMaxDepth;
}
if (_dateFormatStringSet)
{
reader.DateFormatString=previousDateFormatString;
}
if (readerisJsonTextReadertextReader&&textReader.PropertyNameTable!=null&&
_contractResolverisDefaultContractResolverresolver&&textReader.PropertyNameTableresolver.GetNameTable())
{
textReader.PropertyNameTable=null;
}
}
/// <summary>
/// Serializes the specified <seecref='Object'/> and writes the JSON structure
/// using the specified <seecref='TextWriter'/>.
/// </summary>
/// <paramname='textWriter'>The <seecref='TextWriter'/> used to write the JSON structure.</param>
/// <paramname='value'>The <seecref='Object'/> to serialize.</param>
publicvoidSerialize(TextWritertextWriter, object? value)
{
Serialize(newJsonTextWriter(textWriter), value);
}
/// <summary>
/// Serializes the specified <seecref='Object'/> and writes the JSON structure
/// using the specified <seecref='JsonWriter'/>.
/// </summary>
/// <paramname='jsonWriter'>The <seecref='JsonWriter'/> used to write the JSON structure.</param>
/// <paramname='value'>The <seecref='Object'/> to serialize.</param>
/// <paramname='objectType'>
/// The type of the value being serialized.
/// This parameter is used when <seecref='JsonSerializer.TypeNameHandling'/> is <seecref='Json.TypeNameHandling.Auto'/> to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
publicvoidSerialize(JsonWriterjsonWriter, object? value, Type? objectType)
{
SerializeInternal(jsonWriter, value, objectType);
}
/// <summary>
/// Serializes the specified <seecref='Object'/> and writes the JSON structure
/// using the specified <seecref='TextWriter'/>.
/// </summary>
/// <paramname='textWriter'>The <seecref='TextWriter'/> used to write the JSON structure.</param>
/// <paramname='value'>The <seecref='Object'/> to serialize.</param>
/// <paramname='objectType'>
/// The type of the value being serialized.
/// This parameter is used when <seecref='TypeNameHandling'/> is Auto to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
publicvoidSerialize(TextWritertextWriter, object? value, TypeobjectType)
{
Serialize(newJsonTextWriter(textWriter), value, objectType);
}
/// <summary>
/// Serializes the specified <seecref='Object'/> and writes the JSON structure
/// using the specified <seecref='JsonWriter'/>.
/// </summary>
/// <paramname='jsonWriter'>The <seecref='JsonWriter'/> used to write the JSON structure.</param>
/// <paramname='value'>The <seecref='Object'/> to serialize.</param>
publicvoidSerialize(JsonWriterjsonWriter, object? value)
{
SerializeInternal(jsonWriter, value, null);
}
privateTraceJsonReaderCreateTraceJsonReader(JsonReaderreader)
{
TraceJsonReadertraceReader=newTraceJsonReader(reader);
if (reader.TokenType!=JsonToken.None)
{
traceReader.WriteCurrentToken();
}
returntraceReader;
}
internalvirtualvoidSerializeInternal(JsonWriterjsonWriter, object? value, Type? objectType)
{
ValidationUtils.ArgumentNotNull(jsonWriter, nameof(jsonWriter));
// set serialization options onto writer
Formatting? previousFormatting=null;
if (_formatting!=null&&jsonWriter.Formatting!=_formatting)
{
previousFormatting=jsonWriter.Formatting;
jsonWriter.Formatting=_formatting.GetValueOrDefault();
}
DateFormatHandling? previousDateFormatHandling=null;
if (_dateFormatHandling!=null&&jsonWriter.DateFormatHandling!=_dateFormatHandling)
{
previousDateFormatHandling=jsonWriter.DateFormatHandling;
jsonWriter.DateFormatHandling=_dateFormatHandling.GetValueOrDefault();
}
DateTimeZoneHandling? previousDateTimeZoneHandling=null;
if (_dateTimeZoneHandling!=null&&jsonWriter.DateTimeZoneHandling!=_dateTimeZoneHandling)
{
previousDateTimeZoneHandling=jsonWriter.DateTimeZoneHandling;
jsonWriter.DateTimeZoneHandling=_dateTimeZoneHandling.GetValueOrDefault();
}
FloatFormatHandling? previousFloatFormatHandling=null;
if (_floatFormatHandling!=null&&jsonWriter.FloatFormatHandling!=_floatFormatHandling)
{
previousFloatFormatHandling=jsonWriter.FloatFormatHandling;
jsonWriter.FloatFormatHandling=_floatFormatHandling.GetValueOrDefault();
}
StringEscapeHandling? previousStringEscapeHandling=null;
if (_stringEscapeHandling!=null&&jsonWriter.StringEscapeHandling!=_stringEscapeHandling)
{
previousStringEscapeHandling=jsonWriter.StringEscapeHandling;
jsonWriter.StringEscapeHandling=_stringEscapeHandling.GetValueOrDefault();
}
CultureInfo? previousCulture=null;
if (_culture!=null&&!_culture.Equals(jsonWriter.Culture))
{
previousCulture=jsonWriter.Culture;
jsonWriter.Culture=_culture;
}
string? previousDateFormatString=null;
if (_dateFormatStringSet&&jsonWriter.DateFormatString!=_dateFormatString)
{
previousDateFormatString=jsonWriter.DateFormatString;
jsonWriter.DateFormatString=_dateFormatString;
}
TraceJsonWriter? traceJsonWriter= (TraceWriter!=null&&TraceWriter.LevelFilter>=TraceLevel.Verbose)
?newTraceJsonWriter(jsonWriter)
:null;
JsonSerializerInternalWriterserializerWriter=newJsonSerializerInternalWriter(this);
serializerWriter.Serialize(traceJsonWriter??jsonWriter, value, objectType);
if (traceJsonWriter!=null)
{
TraceWriter!.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null);
}
// reset writer back to previous options
if (previousFormatting!=null)
{
jsonWriter.Formatting=previousFormatting.GetValueOrDefault();
}
if (previousDateFormatHandling!=null)
{
jsonWriter.DateFormatHandling=previousDateFormatHandling.GetValueOrDefault();
}
if (previousDateTimeZoneHandling!=null)
{
jsonWriter.DateTimeZoneHandling=previousDateTimeZoneHandling.GetValueOrDefault();
}
if (previousFloatFormatHandling!=null)
{
jsonWriter.FloatFormatHandling=previousFloatFormatHandling.GetValueOrDefault();
}
if (previousStringEscapeHandling!=null)
{
jsonWriter.StringEscapeHandling=previousStringEscapeHandling.GetValueOrDefault();
}
if (_dateFormatStringSet)
{
jsonWriter.DateFormatString=previousDateFormatString;
}
if (previousCulture!=null)
{
jsonWriter.Culture=previousCulture;
}
}
internalIReferenceResolverGetReferenceResolver()
{
if (_referenceResolvernull)
{
_referenceResolver=newDefaultReferenceResolver();
}
return_referenceResolver;
}
internalJsonConverter? GetMatchingConverter(Typetype)
{
returnGetMatchingConverter(_converters, type);
}
internalstaticJsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, TypeobjectType)
{
#ifDEBUG
ValidationUtils.ArgumentNotNull(objectType, nameof(objectType));
#endif
if (converters!=null)
{
for (inti=0; i<converters.Count; i++)
{
JsonConverterconverter=converters[i];
if (converter.CanConvert(objectType))
{
returnconverter;
}
}
}
returnnull;
}
internalvoidOnError(ErrorEventArgse)
{
Error?.Invoke(this, e);
}
}
}

Newtonsoft.json.dll

  • Copy lines
  • Copy permalink