From bf2e2a78e8febf0006ec647f9bde3aa5bbe0ce72 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Mon, 16 May 2022 16:12:52 +0800 Subject: [PATCH] Add .NET 6 target (#2677) --- Build/build.ps1 | 3 +- .../Linq/JObjectTests.cs | 2 +- .../Newtonsoft.Json.Tests.csproj | 29 +++- .../Converters/BinaryConverter.cs | 4 +- .../Converters/DataSetConverter.cs | 4 +- .../Converters/DataTableConverter.cs | 6 +- .../Converters/DiscriminatedUnionConverter.cs | 2 +- .../Converters/EntityKeyMemberConverter.cs | 2 +- .../Converters/ExpandoObjectConverter.cs | 2 +- .../Converters/IsoDateTimeConverter.cs | 4 +- .../Converters/JavaScriptDateTimeConverter.cs | 2 +- .../Converters/KeyValuePairConverter.cs | 6 +- .../Converters/RegexConverter.cs | 2 +- .../Converters/StringEnumConverter.cs | 4 +- .../Converters/UnixDateTimeConverter.cs | 2 +- .../Converters/XmlNodeConverter.cs | 140 ++++++++++-------- Src/Newtonsoft.Json/JsonConvert.cs | 4 +- Src/Newtonsoft.Json/JsonReader.cs | 4 +- Src/Newtonsoft.Json/JsonTextReader.Async.cs | 6 +- Src/Newtonsoft.Json/JsonTextReader.cs | 1 + Src/Newtonsoft.Json/JsonTextWriter.Async.cs | 20 +-- Src/Newtonsoft.Json/JsonTextWriter.cs | 7 + Src/Newtonsoft.Json/JsonWriter.Async.cs | 10 +- Src/Newtonsoft.Json/JsonWriter.cs | 4 +- Src/Newtonsoft.Json/Linq/Extensions.cs | 4 +- Src/Newtonsoft.Json/Linq/JConstructor.cs | 8 +- Src/Newtonsoft.Json/Linq/JContainer.Async.cs | 2 +- Src/Newtonsoft.Json/Linq/JContainer.cs | 25 ++-- Src/Newtonsoft.Json/Linq/JEnumerable.cs | 2 +- Src/Newtonsoft.Json/Linq/JObject.Async.cs | 4 +- Src/Newtonsoft.Json/Linq/JObject.cs | 6 +- Src/Newtonsoft.Json/Linq/JProperty.Async.cs | 2 +- Src/Newtonsoft.Json/Linq/JProperty.cs | 8 +- .../Linq/JPropertyDescriptor.cs | 4 +- .../Linq/JPropertyKeyedCollection.cs | 4 +- Src/Newtonsoft.Json/Linq/JToken.cs | 18 +-- .../Linq/JTokenEqualityComparer.cs | 2 +- Src/Newtonsoft.Json/Linq/JValue.cs | 50 +++---- .../Linq/JsonPath/QueryExpression.cs | 2 +- Src/Newtonsoft.Json/Newtonsoft.Json.csproj | 8 +- .../Schema/JsonSchemaBuilder.cs | 11 +- .../CamelCasePropertyNamesContractResolver.cs | 2 +- .../Serialization/DefaultContractResolver.cs | 40 ++--- .../Serialization/DefaultReferenceResolver.cs | 6 +- .../DefaultSerializationBinder.cs | 10 +- .../Serialization/JsonArrayContract.cs | 5 +- .../Serialization/JsonContract.cs | 2 +- .../Serialization/JsonDictionaryContract.cs | 4 +- .../Serialization/JsonFormatterConverter.cs | 8 +- .../Serialization/JsonPropertyCollection.cs | 4 +- .../JsonSerializerInternalBase.cs | 2 +- .../JsonSerializerInternalReader.cs | 28 ++-- .../JsonSerializerInternalWriter.cs | 12 +- .../Serialization/JsonTypeReflector.cs | 19 ++- .../Serialization/NamingStrategy.cs | 2 +- .../SerializationBinderAdapter.cs | 2 +- Src/Newtonsoft.Json/Utilities/AsyncUtils.cs | 6 +- .../Utilities/Base64Encoder.cs | 10 +- .../Utilities/BidirectionalDictionary.cs | 11 +- .../Utilities/CollectionUtils.cs | 12 +- .../Utilities/CollectionWrapper.cs | 30 ++-- Src/Newtonsoft.Json/Utilities/ConvertUtils.cs | 8 +- .../Utilities/DictionaryWrapper.cs | 34 ++--- .../Utilities/DynamicProxyMetaObject.cs | 16 +- .../DynamicReflectionDelegateFactory.cs | 38 ++--- Src/Newtonsoft.Json/Utilities/DynamicUtils.cs | 24 +-- Src/Newtonsoft.Json/Utilities/EnumUtils.cs | 4 +- .../ExpressionReflectionDelegateFactory.cs | 22 +-- Src/Newtonsoft.Json/Utilities/FSharpUtils.cs | 26 ++-- .../Utilities/ImmutableCollectionsUtils.cs | 20 +-- .../Utilities/JavaScriptUtils.cs | 5 +- .../LateBoundReflectionDelegateFactory.cs | 10 +- .../Utilities/MiscellaneousUtils.cs | 4 +- .../Utilities/NullableAttributes.cs | 6 +- .../Utilities/ReflectionUtils.cs | 34 +++-- Src/Newtonsoft.Json/Utilities/StringBuffer.cs | 2 +- Src/Newtonsoft.Json/Utilities/StringUtils.cs | 20 ++- .../Utilities/StructMultiKey.cs | 2 +- .../Utilities/ThreadSafeStore.cs | 2 +- .../Utilities/TypeExtensions.cs | 6 +- 80 files changed, 520 insertions(+), 408 deletions(-) diff --git a/Build/build.ps1 b/Build/build.ps1 index 7491dc6f..d5927e26 100644 --- a/Build/build.ps1 +++ b/Build/build.ps1 @@ -32,7 +32,8 @@ $nunitConsolePath = "$buildDir\Temp\NUnit.ConsoleRunner.$nunitConsoleVersion" $builds = @( - @{Framework = "netstandard2.0"; TestsFunction = "NetCliTests"; TestFramework = "net6.0"; Enabled=$true}, + @{Framework = "net6.0"; TestsFunction = "NetCliTests"; TestFramework = "net6.0"; Enabled=$true}, + @{Framework = "netstandard2.0"; TestsFunction = "NetCliTests"; TestFramework = "net5.0"; Enabled=$true}, @{Framework = "netstandard1.3"; TestsFunction = "NetCliTests"; TestFramework = "netcoreapp3.1"; Enabled=$true}, @{Framework = "netstandard1.0"; TestsFunction = "NetCliTests"; TestFramework = "netcoreapp2.1"; Enabled=$true}, @{Framework = "net45"; TestsFunction = "NUnitTests"; TestFramework = "net46"; NUnitFramework="net-4.0"; Enabled=$true}, diff --git a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs index 03f69e08..47d7a078 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs @@ -1439,7 +1439,7 @@ Parameter name: arrayIndex", ITypedList l = new JObject(p1, p2); PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null); - Assert.IsNull(propertyDescriptors); + Assert.AreEqual(0, propertyDescriptors.Count); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj index f1166b1a..d716b0a8 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -1,6 +1,6 @@  - net46;net40;net35;net20;net6.0;netcoreapp3.1;netcoreapp2.1 + net46;net40;net35;net20;net5.0;net6.0;netcoreapp3.1;netcoreapp2.1 $(TestFrameworks) 9.0 1.0 @@ -13,7 +13,7 @@ Newtonsoft.Json.Tests false - Full + Full false @@ -109,6 +109,27 @@ NET20;$(AdditionalConstants) + + + + + + + + + + + + + + + + + Json.NET Tests .NET Standard 2.0 + .NETStandard,Version=v2.0 + NETSTANDARD2_0;DNXCORE50;PORTABLE;HAVE_BENCHMARKS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) + + @@ -125,8 +146,8 @@ - Json.NET Tests .NET Standard 2.0 - .NETStandard,Version=v2.0 + Json.NET Tests .NET 6.0 + net6.0 NETSTANDARD2_0;DNXCORE50;PORTABLE;HAVE_BENCHMARKS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) diff --git a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs index 7390503a..47833a2a 100644 --- a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs +++ b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs @@ -126,7 +126,7 @@ namespace Newtonsoft.Json.Converters { // current token is already at base64 string // unable to call ReadAsBytes so do it the old fashion way - string encodedData = reader.Value!.ToString(); + string encodedData = reader.Value!.ToString()!; data = Convert.FromBase64String(encodedData); } else @@ -135,7 +135,7 @@ namespace Newtonsoft.Json.Converters } Type t = (ReflectionUtils.IsNullableType(objectType)) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; #if HAVE_LINQ diff --git a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs index 61bb6253..214728e6 100644 --- a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs @@ -84,7 +84,7 @@ namespace Newtonsoft.Json.Converters // handle typed datasets DataSet ds = (objectType == typeof(DataSet)) ? new DataSet() - : (DataSet)Activator.CreateInstance(objectType); + : (DataSet)Activator.CreateInstance(objectType)!; DataTableConverter converter = new DataTableConverter(); @@ -92,7 +92,7 @@ namespace Newtonsoft.Json.Converters while (reader.TokenType == JsonToken.PropertyName) { - DataTable dt = ds.Tables[(string)reader.Value!]; + DataTable? dt = ds.Tables[(string)reader.Value!]; bool exists = (dt != null); dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer)!; diff --git a/Src/Newtonsoft.Json/Converters/DataTableConverter.cs b/Src/Newtonsoft.Json/Converters/DataTableConverter.cs index 7f8c529e..1a32e512 100644 --- a/Src/Newtonsoft.Json/Converters/DataTableConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DataTableConverter.cs @@ -99,7 +99,7 @@ namespace Newtonsoft.Json.Converters // handle typed datasets dt = (objectType == typeof(DataTable)) ? new DataTable() - : (DataTable)Activator.CreateInstance(objectType); + : (DataTable)Activator.CreateInstance(objectType)!; } // DataTable is inside a DataSet @@ -144,7 +144,7 @@ namespace Newtonsoft.Json.Converters reader.ReadAndAssert(); - DataColumn column = dt.Columns[columnName]; + DataColumn? column = dt.Columns[columnName]; if (column == null) { Type columnType = GetColumnDataType(reader); @@ -185,7 +185,7 @@ namespace Newtonsoft.Json.Converters reader.ReadAndAssert(); } - Array destinationArray = Array.CreateInstance(column.DataType.GetElementType(), o.Count); + Array destinationArray = Array.CreateInstance(column.DataType.GetElementType()!, o.Count); ((IList)o).CopyTo(destinationArray, 0); dr[columnName] = destinationArray; diff --git a/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs b/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs index 5adb40b2..c4c5d08a 100644 --- a/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs @@ -182,7 +182,7 @@ namespace Newtonsoft.Json.Converters while (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (string.Equals(propertyName, CasePropertyName, StringComparison.OrdinalIgnoreCase)) { reader.ReadAndAssert(); diff --git a/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs b/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs index 4670dba4..757c8fac 100644 --- a/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs +++ b/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs @@ -129,7 +129,7 @@ namespace Newtonsoft.Json.Converters reader.ReadAndAssert(); string? type = reader.Value?.ToString(); - Type t = Type.GetType(type); + Type t = Type.GetType(type!)!; ReadAndAssertProperty(reader, ValuePropertyName); reader.ReadAndAssert(); diff --git a/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs b/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs index 0b5153fd..5a674b8c 100644 --- a/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs +++ b/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs @@ -119,7 +119,7 @@ namespace Newtonsoft.Json.Converters switch (reader.TokenType) { case JsonToken.PropertyName: - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (!reader.Read()) { diff --git a/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs index d9c8ee23..de9b1bb5 100644 --- a/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs @@ -133,7 +133,7 @@ namespace Newtonsoft.Json.Converters #if HAVE_DATE_TIME_OFFSET Type t = (nullable) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; #endif @@ -167,6 +167,8 @@ namespace Newtonsoft.Json.Converters return null; } + MiscellaneousUtils.Assert(dateText != null); + #if HAVE_DATE_TIME_OFFSET if (t == typeof(DateTimeOffset)) { diff --git a/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs index 34082451..ff1231f2 100644 --- a/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs @@ -98,7 +98,7 @@ namespace Newtonsoft.Json.Converters #if HAVE_DATE_TIME_OFFSET Type t = (ReflectionUtils.IsNullableType(objectType)) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; if (t == typeof(DateTimeOffset)) { diff --git a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs index 0f12f1fa..0221e933 100644 --- a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs +++ b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs @@ -102,7 +102,7 @@ namespace Newtonsoft.Json.Converters reader.ReadAndAssert(); Type t = ReflectionUtils.IsNullableType(objectType) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; ReflectionObject reflectionObject = ReflectionObjectPerType.Get(t); @@ -111,7 +111,7 @@ namespace Newtonsoft.Json.Converters while (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase)) { reader.ReadForTypeAndAssert(keyContract, false); @@ -145,7 +145,7 @@ namespace Newtonsoft.Json.Converters public override bool CanConvert(Type objectType) { Type t = (ReflectionUtils.IsNullableType(objectType)) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; if (t.IsValueType() && t.IsGenericType()) diff --git a/Src/Newtonsoft.Json/Converters/RegexConverter.cs b/Src/Newtonsoft.Json/Converters/RegexConverter.cs index 8bf6e9f9..13db1bb5 100644 --- a/Src/Newtonsoft.Json/Converters/RegexConverter.cs +++ b/Src/Newtonsoft.Json/Converters/RegexConverter.cs @@ -179,7 +179,7 @@ namespace Newtonsoft.Json.Converters switch (reader.TokenType) { case JsonToken.PropertyName: - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (!reader.Read()) { diff --git a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs index 9ba6b632..a9840080 100644 --- a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs +++ b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs @@ -222,7 +222,7 @@ namespace Newtonsoft.Json.Converters } bool isNullable = ReflectionUtils.IsNullableType(objectType); - Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType; + Type t = isNullable ? Nullable.GetUnderlyingType(objectType)! : objectType; try { @@ -267,7 +267,7 @@ namespace Newtonsoft.Json.Converters public override bool CanConvert(Type objectType) { Type t = (ReflectionUtils.IsNullableType(objectType)) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; return t.IsEnum(); diff --git a/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs index a211813d..7d0700e0 100644 --- a/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs @@ -144,7 +144,7 @@ namespace Newtonsoft.Json.Converters DateTime d = UnixEpoch.AddSeconds(seconds); #if HAVE_DATE_TIME_OFFSET - Type t = (nullable) + Type? t = (nullable) ? Nullable.GetUnderlyingType(objectType) : objectType; if (t == typeof(DateTimeOffset)) diff --git a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs index 2abb677a..12bde515 100644 --- a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs @@ -79,19 +79,19 @@ namespace Newtonsoft.Json.Converters return new XmlNodeWrapper(_document.CreateSignificantWhitespace(text)); } - public IXmlNode CreateXmlDeclaration(string? version, string? encoding, string? standalone) + public IXmlNode CreateXmlDeclaration(string version, string? encoding, string? standalone) { return new XmlDeclarationWrapper(_document.CreateXmlDeclaration(version, encoding, standalone)); } #if HAVE_XML_DOCUMENT_TYPE - public IXmlNode CreateXmlDocumentType(string? name, string? publicId, string? systemId, string? internalSubset) + public IXmlNode CreateXmlDocumentType(string name, string? publicId, string? systemId, string? internalSubset) { return new XmlDocumentTypeWrapper(_document.CreateDocumentType(name, publicId, systemId, null)); } #endif - public IXmlNode CreateProcessingInstruction(string target, string? data) + public IXmlNode CreateProcessingInstruction(string target, string data) { return new XmlNodeWrapper(_document.CreateProcessingInstruction(target, data)); } @@ -114,7 +114,7 @@ namespace Newtonsoft.Json.Converters return attribute; } - public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value) + public IXmlNode CreateAttribute(string qualifiedName, string? namespaceUri, string? value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceUri)); attribute.Value = value; @@ -153,7 +153,7 @@ namespace Newtonsoft.Json.Converters _element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode!); } - public string GetPrefixOfNamespace(string namespaceUri) + public string? GetPrefixOfNamespace(string namespaceUri) { return _element.GetPrefixOfNamespace(namespaceUri); } @@ -171,15 +171,15 @@ namespace Newtonsoft.Json.Converters _declaration = declaration; } - public string Version => _declaration.Version; + public string? Version => _declaration.Version; - public string Encoding + public string? Encoding { get => _declaration.Encoding; set => _declaration.Encoding = value; } - public string Standalone + public string? Standalone { get => _declaration.Standalone; set => _declaration.Standalone = value; @@ -199,11 +199,11 @@ namespace Newtonsoft.Json.Converters public string Name => _documentType.Name; - public string System => _documentType.SystemId; + public string? System => _documentType.SystemId; - public string Public => _documentType.PublicId; + public string? Public => _documentType.PublicId; - public string InternalSubset => _documentType.InternalSubset; + public string? InternalSubset => _documentType.InternalSubset; public override string? LocalName => "DOCTYPE"; } @@ -285,7 +285,7 @@ namespace Newtonsoft.Json.Converters } else { - _attributes = new List(_node.Attributes.Count); + _attributes = new List(_node.Attributes!.Count); foreach (XmlAttribute attribute in _node.Attributes) { _attributes.Add(WrapNode(attribute)); @@ -314,7 +314,7 @@ namespace Newtonsoft.Json.Converters { get { - XmlNode node = _node is XmlAttribute attribute ? attribute.OwnerElement : _node.ParentNode; + XmlNode? node = _node is XmlAttribute attribute ? attribute.OwnerElement : _node.ParentNode; if (node == null) { @@ -354,38 +354,38 @@ namespace Newtonsoft.Json.Converters IXmlNode CreateCDataSection(string? data); IXmlNode CreateWhitespace(string? text); IXmlNode CreateSignificantWhitespace(string? text); - IXmlNode CreateXmlDeclaration(string? version, string? encoding, string? standalone); + IXmlNode CreateXmlDeclaration(string version, string? encoding, string? standalone); #if HAVE_XML_DOCUMENT_TYPE - IXmlNode CreateXmlDocumentType(string? name, string? publicId, string? systemId, string? internalSubset); + IXmlNode CreateXmlDocumentType(string name, string? publicId, string? systemId, string? internalSubset); #endif - IXmlNode CreateProcessingInstruction(string target, string? data); + IXmlNode CreateProcessingInstruction(string target, string data); IXmlElement CreateElement(string elementName); IXmlElement CreateElement(string qualifiedName, string namespaceUri); - IXmlNode CreateAttribute(string name, string? value); - IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value); + IXmlNode CreateAttribute(string name, string value); + IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value); IXmlElement? DocumentElement { get; } } internal interface IXmlDeclaration : IXmlNode { - string Version { get; } - string Encoding { get; set; } - string Standalone { get; set; } + string? Version { get; } + string? Encoding { get; set; } + string? Standalone { get; set; } } internal interface IXmlDocumentType : IXmlNode { string Name { get; } - string System { get; } - string Public { get; } - string InternalSubset { get; } + string? System { get; } + string? Public { get; } + string? InternalSubset { get; } } internal interface IXmlElement : IXmlNode { void SetAttributeNode(IXmlNode attribute); - string GetPrefixOfNamespace(string namespaceUri); + string? GetPrefixOfNamespace(string namespaceUri); bool IsEmpty { get; } } @@ -417,15 +417,15 @@ namespace Newtonsoft.Json.Converters public override XmlNodeType NodeType => XmlNodeType.XmlDeclaration; - public string Version => Declaration.Version; + public string? Version => Declaration.Version; - public string Encoding + public string? Encoding { get => Declaration.Encoding; set => Declaration.Encoding = value; } - public string Standalone + public string? Standalone { get => Declaration.Standalone; set => Declaration.Standalone = value; @@ -444,11 +444,11 @@ namespace Newtonsoft.Json.Converters public string Name => _documentType.Name; - public string System => _documentType.SystemId; + public string? System => _documentType.SystemId; - public string Public => _documentType.PublicId; + public string? Public => _documentType.PublicId; - public string InternalSubset => _documentType.InternalSubset; + public string? InternalSubset => _documentType.InternalSubset; public override string? LocalName => "DOCTYPE"; } @@ -491,40 +491,40 @@ namespace Newtonsoft.Json.Converters public IXmlNode CreateComment(string? text) { - return new XObjectWrapper(new XComment(text)); + return new XObjectWrapper(new XComment(text!)); } public IXmlNode CreateTextNode(string? text) { - return new XObjectWrapper(new XText(text)); + return new XObjectWrapper(new XText(text!)); } public IXmlNode CreateCDataSection(string? data) { - return new XObjectWrapper(new XCData(data)); + return new XObjectWrapper(new XCData(data!)); } public IXmlNode CreateWhitespace(string? text) { - return new XObjectWrapper(new XText(text)); + return new XObjectWrapper(new XText(text!)); } public IXmlNode CreateSignificantWhitespace(string? text) { - return new XObjectWrapper(new XText(text)); + return new XObjectWrapper(new XText(text!)); } - public IXmlNode CreateXmlDeclaration(string? version, string? encoding, string? standalone) + public IXmlNode CreateXmlDeclaration(string version, string? encoding, string? standalone) { return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone)); } - public IXmlNode CreateXmlDocumentType(string? name, string? publicId, string? systemId, string? internalSubset) + public IXmlNode CreateXmlDocumentType(string name, string? publicId, string? systemId, string? internalSubset) { return new XDocumentTypeWrapper(new XDocumentType(name, publicId, systemId, internalSubset)); } - public IXmlNode CreateProcessingInstruction(string target, string? data) + public IXmlNode CreateProcessingInstruction(string target, string data) { return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data)); } @@ -540,12 +540,12 @@ namespace Newtonsoft.Json.Converters return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri))); } - public IXmlNode CreateAttribute(string name, string? value) + public IXmlNode CreateAttribute(string name, string value) { return new XAttributeWrapper(new XAttribute(name, value)); } - public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value) + public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value)); @@ -590,7 +590,7 @@ namespace Newtonsoft.Json.Converters public override string? Value { get => Text.Value; - set => Text.Value = value; + set => Text.Value = value ?? string.Empty; } public override IXmlNode? ParentNode @@ -619,7 +619,7 @@ namespace Newtonsoft.Json.Converters public override string? Value { get => Text.Value; - set => Text.Value = value; + set => Text.Value = value ?? string.Empty; } public override IXmlNode? ParentNode @@ -650,7 +650,7 @@ namespace Newtonsoft.Json.Converters public override string? Value { get => ProcessingInstruction.Data; - set => ProcessingInstruction.Data = value; + set => ProcessingInstruction.Data = value ?? string.Empty; } } @@ -807,7 +807,7 @@ namespace Newtonsoft.Json.Converters public override string? Value { get => Attribute.Value; - set => Attribute.Value = value; + set => Attribute.Value = value ?? string.Empty; } public override string? LocalName => Attribute.Name.LocalName; @@ -919,14 +919,14 @@ namespace Newtonsoft.Json.Converters public override string? Value { get => Element.Value; - set => Element.Value = value; + set => Element.Value = value ?? string.Empty; } public override string? LocalName => Element.Name.LocalName; public override string? NamespaceUri => Element.Name.NamespaceName; - public string GetPrefixOfNamespace(string namespaceUri) + public string? GetPrefixOfNamespace(string namespaceUri) { return Element.GetPrefixOfNamespace(namespaceUri); } @@ -1059,7 +1059,7 @@ namespace Newtonsoft.Json.Converters { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns") { - manager.AddNamespace(attribute.LocalName, attribute.Value); + manager.AddNamespace(attribute.LocalName!, attribute.Value!); } } } @@ -1078,7 +1078,7 @@ namespace Newtonsoft.Json.Converters } else { - return XmlConvert.DecodeName(node.LocalName); + return XmlConvert.DecodeName(node.LocalName)!; } } @@ -1131,7 +1131,7 @@ namespace Newtonsoft.Json.Converters { if (attribute.LocalName == "Array" && attribute.NamespaceUri == JsonNamespaceUri) { - return XmlConvert.ToBoolean(attribute.Value); + return XmlConvert.ToBoolean(attribute.Value!); } } @@ -1201,7 +1201,7 @@ namespace Newtonsoft.Json.Converters } else { - if (!nodesGroupedByName.TryGetValue(currentNodeName, out object value)) + if (!nodesGroupedByName.TryGetValue(currentNodeName, out object? value)) { nodesGroupedByName.Add(currentNodeName, childNode); } @@ -1314,7 +1314,7 @@ namespace Newtonsoft.Json.Converters if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/") { string namespacePrefix = (attribute.LocalName != "xmlns") - ? XmlConvert.DecodeName(attribute.LocalName) + ? XmlConvert.DecodeName(attribute.LocalName)! : string.Empty; string? namespaceUri = attribute.Value; if (namespaceUri == null) @@ -1654,7 +1654,7 @@ namespace Newtonsoft.Json.Converters case JsonTypeReflector.TypePropertyName: case JsonTypeReflector.ValuePropertyName: string attributeName = propertyName.Substring(1); - string attributePrefix = manager.LookupPrefix(JsonNamespaceUri); + string? attributePrefix = manager.LookupPrefix(JsonNamespaceUri); AddAttribute(reader, document, currentNode, propertyName, attributeName, manager, attributePrefix); return; } @@ -1685,7 +1685,9 @@ namespace Newtonsoft.Json.Converters string encodedName = XmlConvert.EncodeName(nameValue.Key); string? attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); - IXmlNode attribute = (!StringUtils.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value) : document.CreateAttribute(encodedName, nameValue.Value); + IXmlNode attribute = (!StringUtils.IsNullOrEmpty(attributePrefix)) + ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value!) + : document.CreateAttribute(encodedName, nameValue.Value!); element.SetAttributeNode(attribute); } @@ -1731,10 +1733,10 @@ namespace Newtonsoft.Json.Converters } string encodedName = XmlConvert.EncodeName(attributeName); - string? attributeValue = ConvertTokenToXmlValue(reader); + string attributeValue = ConvertTokenToXmlValue(reader)!; IXmlNode attribute = (!StringUtils.IsNullOrEmpty(attributePrefix)) - ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix), attributeValue) + ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix)!, attributeValue) : document.CreateAttribute(encodedName, attributeValue); ((IXmlElement)currentNode).SetAttributeNode(attribute); @@ -1874,7 +1876,7 @@ namespace Newtonsoft.Json.Converters switch (reader.TokenType) { case JsonToken.PropertyName: - string attributeName = reader.Value!.ToString(); + string attributeName = reader.Value!.ToString()!; if (!StringUtils.IsNullOrEmpty(attributeName)) { @@ -1896,7 +1898,7 @@ namespace Newtonsoft.Json.Converters if (IsNamespaceAttribute(attributeName, out string? namespacePrefix)) { - manager.AddNamespace(namespacePrefix, attributeValue); + manager.AddNamespace(namespacePrefix, attributeValue!); } break; case '$': @@ -1909,7 +1911,7 @@ namespace Newtonsoft.Json.Converters case JsonTypeReflector.ValuePropertyName: // check that JsonNamespaceUri is in scope // if it isn't then add it to document and namespace manager - string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri); + string? jsonPrefix = manager.LookupPrefix(JsonNamespaceUri); if (jsonPrefix == null) { if (attributeNameValues == null) @@ -2008,12 +2010,17 @@ namespace Newtonsoft.Json.Converters } } + if (version == null) + { + throw JsonSerializationException.Create(reader, "Version not specified for XML declaration."); + } + IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone); currentNode.AppendChild(declaration); } else { - IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), ConvertTokenToXmlValue(reader)); + IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), ConvertTokenToXmlValue(reader)!); currentNode.AppendChild(instruction); } } @@ -2050,6 +2057,11 @@ namespace Newtonsoft.Json.Converters } } + if (name == null) + { + throw JsonSerializationException.Create(reader, "Name not specified for XML document type."); + } + IXmlNode documentType = document.CreateXmlDocumentType(name, publicId, systemId, internalSubset); currentNode.AppendChild(documentType); } @@ -2058,7 +2070,7 @@ namespace Newtonsoft.Json.Converters private IXmlElement CreateElement(string elementName, IXmlDocument document, string? elementPrefix, XmlNamespaceManager manager) { string encodeName = EncodeSpecialCharacters ? XmlConvert.EncodeLocalName(elementName) : XmlConvert.EncodeName(elementName); - string ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); + string? ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); IXmlElement element = (!StringUtils.IsNullOrEmpty(ns)) ? document.CreateElement(encodeName, ns) : document.CreateElement(encodeName); @@ -2077,7 +2089,7 @@ namespace Newtonsoft.Json.Converters throw JsonSerializationException.Create(reader, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifying a DeserializeRootElementName."); } - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; reader.ReadAndAssert(); if (reader.TokenType == JsonToken.StartArray) @@ -2092,7 +2104,7 @@ namespace Newtonsoft.Json.Converters if (count == 1 && WriteArrayAttribute) { MiscellaneousUtils.GetQualifiedNameParts(propertyName, out string? elementPrefix, out string localName); - string ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); + string? ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); foreach (IXmlNode childNode in currentNode.ChildNodes) { @@ -2110,7 +2122,7 @@ namespace Newtonsoft.Json.Converters } continue; case JsonToken.StartConstructor: - string constructorName = reader.Value!.ToString(); + string constructorName = reader.Value!.ToString()!; while (reader.Read() && reader.TokenType != JsonToken.EndConstructor) { diff --git a/Src/Newtonsoft.Json/JsonConvert.cs b/Src/Newtonsoft.Json/JsonConvert.cs index 5bf7e2a6..95019e2b 100644 --- a/Src/Newtonsoft.Json/JsonConvert.cs +++ b/Src/Newtonsoft.Json/JsonConvert.cs @@ -302,7 +302,7 @@ namespace Newtonsoft.Json private static string EnsureDecimalPlace(double value, string text) { - if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1) + if (double.IsNaN(value) || double.IsInfinity(value) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1) { return text; } @@ -312,7 +312,7 @@ namespace Newtonsoft.Json private static string EnsureDecimalPlace(string text) { - if (text.IndexOf('.') != -1) + if (StringUtils.IndexOf(text, '.') != -1) { return text; } diff --git a/Src/Newtonsoft.Json/JsonReader.cs b/Src/Newtonsoft.Json/JsonReader.cs index 2351b187..e368afc1 100644 --- a/Src/Newtonsoft.Json/JsonReader.cs +++ b/Src/Newtonsoft.Json/JsonReader.cs @@ -496,7 +496,7 @@ namespace Newtonsoft.Json } else { - s = v is Uri uri ? uri.OriginalString : v.ToString(); + s = v is Uri uri ? uri.OriginalString : v.ToString()!; } SetToken(JsonToken.String, s, false); @@ -940,7 +940,7 @@ namespace Newtonsoft.Json if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName) { ReaderReadAndAssert(); - if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) + if (Value != null && Value.ToString()!.StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) diff --git a/Src/Newtonsoft.Json/JsonTextReader.Async.cs b/Src/Newtonsoft.Json/JsonTextReader.Async.cs index 7963f5b9..8974e700 100644 --- a/Src/Newtonsoft.Json/JsonTextReader.Async.cs +++ b/Src/Newtonsoft.Json/JsonTextReader.Async.cs @@ -79,7 +79,7 @@ namespace Newtonsoft.Json return ParseObjectAsync(cancellationToken); case State.PostValue: Task task = ParsePostValueAsync(false, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { if (task.Result) { @@ -542,7 +542,7 @@ namespace Newtonsoft.Json _charPos++; Task task = EnsureCharsAsync(1, append, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { SetNewLine(task.Result); return AsyncUtils.CompletedTask; @@ -1680,7 +1680,7 @@ namespace Newtonsoft.Json if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName) { await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false); - if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) + if (Value != null && Value.ToString()!.StartsWith("System.Byte[]", StringComparison.Ordinal)) { await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) diff --git a/Src/Newtonsoft.Json/JsonTextReader.cs b/Src/Newtonsoft.Json/JsonTextReader.cs index 6b107b0e..925f4b6b 100644 --- a/Src/Newtonsoft.Json/JsonTextReader.cs +++ b/Src/Newtonsoft.Json/JsonTextReader.cs @@ -2353,6 +2353,7 @@ namespace Newtonsoft.Json { if (setToken) { + MiscellaneousUtils.Assert(_chars != null); SetToken(JsonToken.Comment, new string(_chars, initialPosition, endPosition - initialPosition)); } } diff --git a/Src/Newtonsoft.Json/JsonTextWriter.Async.cs b/Src/Newtonsoft.Json/JsonTextWriter.Async.cs index c1c763e9..f3ac2398 100644 --- a/Src/Newtonsoft.Json/JsonTextWriter.Async.cs +++ b/Src/Newtonsoft.Json/JsonTextWriter.Async.cs @@ -190,7 +190,7 @@ namespace Newtonsoft.Json private Task WriteValueInternalAsync(JsonToken token, string value, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(token, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return _writer.WriteAsync(value, cancellationToken); } @@ -270,7 +270,7 @@ namespace Newtonsoft.Json private Task WriteIntegerValueAsync(ulong uvalue, bool negative, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.Integer, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return WriteDigitsAsync(uvalue, negative, cancellationToken); } @@ -321,13 +321,13 @@ namespace Newtonsoft.Json internal Task DoWritePropertyNameAsync(string name, CancellationToken cancellationToken) { Task task = InternalWritePropertyNameAsync(name, cancellationToken); - if (!task.IsCompletedSucessfully()) + if (!task.IsCompletedSuccessfully()) { return DoWritePropertyNameAsync(task, name, cancellationToken); } task = WriteEscapedStringAsync(name, _quoteName, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return _writer.WriteAsync(':', cancellationToken); } @@ -399,7 +399,7 @@ namespace Newtonsoft.Json internal Task DoWriteStartArrayAsync(CancellationToken cancellationToken) { Task task = InternalWriteStartAsync(JsonToken.StartArray, JsonContainerType.Array, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return _writer.WriteAsync('[', cancellationToken); } @@ -429,7 +429,7 @@ namespace Newtonsoft.Json internal Task DoWriteStartObjectAsync(CancellationToken cancellationToken) { Task task = InternalWriteStartAsync(JsonToken.StartObject, JsonContainerType.Object, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return _writer.WriteAsync('{', cancellationToken); } @@ -481,7 +481,7 @@ namespace Newtonsoft.Json internal Task DoWriteUndefinedAsync(CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.Undefined, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return _writer.WriteAsync(JsonConvert.Undefined, cancellationToken); } @@ -1058,7 +1058,7 @@ namespace Newtonsoft.Json internal Task DoWriteValueAsync(string? value, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.String, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return value == null ? _writer.WriteAsync(JsonConvert.Null, cancellationToken) : WriteEscapedStringAsync(value, true, cancellationToken); } @@ -1193,7 +1193,7 @@ namespace Newtonsoft.Json internal Task WriteValueNotNullAsync(Uri value, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.String, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return WriteEscapedStringAsync(value.OriginalString, true, cancellationToken); } @@ -1314,7 +1314,7 @@ namespace Newtonsoft.Json { UpdateScopeWithFinishedValue(); Task task = AutoCompleteAsync(JsonToken.Undefined, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return WriteRawAsync(json, cancellationToken); } diff --git a/Src/Newtonsoft.Json/JsonTextWriter.cs b/Src/Newtonsoft.Json/JsonTextWriter.cs index b08dfb48..888bb04d 100644 --- a/Src/Newtonsoft.Json/JsonTextWriter.cs +++ b/Src/Newtonsoft.Json/JsonTextWriter.cs @@ -325,6 +325,7 @@ namespace Newtonsoft.Json int newLineLen = SetIndentChars(); + MiscellaneousUtils.Assert(_indentChars != null); _writer.Write(_indentChars, 0, newLineLen + Math.Min(currentIndentCount, IndentCharBufferSize)); while ((currentIndentCount -= IndentCharBufferSize) > 0) @@ -637,6 +638,7 @@ namespace Newtonsoft.Json { int length = WriteValueToBuffer(value); + MiscellaneousUtils.Assert(_writeBuffer != null); _writer.Write(_writeBuffer, 0, length); } else @@ -692,6 +694,7 @@ namespace Newtonsoft.Json { int length = WriteValueToBuffer(value); + MiscellaneousUtils.Assert(_writeBuffer != null); _writer.Write(_writeBuffer, 0, length); } else @@ -829,6 +832,8 @@ namespace Newtonsoft.Json else { int length = WriteNumberToBuffer(value, negative); + + MiscellaneousUtils.Assert(_writeBuffer != null); _writer.Write(_writeBuffer, 0, length); } } @@ -887,6 +892,8 @@ namespace Newtonsoft.Json else { int length = WriteNumberToBuffer(value, negative); + + MiscellaneousUtils.Assert(_writeBuffer != null); _writer.Write(_writeBuffer, 0, length); } } diff --git a/Src/Newtonsoft.Json/JsonWriter.Async.cs b/Src/Newtonsoft.Json/JsonWriter.Async.cs index 750d2927..4610594c 100644 --- a/Src/Newtonsoft.Json/JsonWriter.Async.cs +++ b/Src/Newtonsoft.Json/JsonWriter.Async.cs @@ -291,7 +291,7 @@ namespace Newtonsoft.Json if (_currentState == State.Property) { t = WriteNullAsync(cancellationToken); - if (!t.IsCompletedSucessfully()) + if (!t.IsCompletedSuccessfully()) { return AwaitProperty(t, levelsToComplete, token, cancellationToken); } @@ -302,7 +302,7 @@ namespace Newtonsoft.Json if (_currentState != State.ObjectStart && _currentState != State.ArrayStart) { t = WriteIndentAsync(cancellationToken); - if (!t.IsCompletedSucessfully()) + if (!t.IsCompletedSuccessfully()) { return AwaitIndent(t, levelsToComplete, token, cancellationToken); } @@ -310,7 +310,7 @@ namespace Newtonsoft.Json } t = WriteEndAsync(token, cancellationToken); - if (!t.IsCompletedSucessfully()) + if (!t.IsCompletedSuccessfully()) { return AwaitEnd(t, levelsToComplete, cancellationToken); } @@ -691,10 +691,10 @@ namespace Newtonsoft.Json return WriteStartArrayAsync(cancellationToken); case JsonToken.StartConstructor: ValidationUtils.ArgumentNotNull(value, nameof(value)); - return WriteStartConstructorAsync(value.ToString(), cancellationToken); + return WriteStartConstructorAsync(value.ToString()!, cancellationToken); case JsonToken.PropertyName: ValidationUtils.ArgumentNotNull(value, nameof(value)); - return WritePropertyNameAsync(value.ToString(), cancellationToken); + return WritePropertyNameAsync(value.ToString()!, cancellationToken); case JsonToken.Comment: return WriteCommentAsync(value?.ToString(), cancellationToken); case JsonToken.Integer: diff --git a/Src/Newtonsoft.Json/JsonWriter.cs b/Src/Newtonsoft.Json/JsonWriter.cs index a68fc8c4..5fd5efe4 100644 --- a/Src/Newtonsoft.Json/JsonWriter.cs +++ b/Src/Newtonsoft.Json/JsonWriter.cs @@ -537,11 +537,11 @@ namespace Newtonsoft.Json break; case JsonToken.StartConstructor: ValidationUtils.ArgumentNotNull(value, nameof(value)); - WriteStartConstructor(value.ToString()); + WriteStartConstructor(value.ToString()!); break; case JsonToken.PropertyName: ValidationUtils.ArgumentNotNull(value, nameof(value)); - WritePropertyName(value.ToString()); + WritePropertyName(value.ToString()!); break; case JsonToken.Comment: WriteComment(value?.ToString()); diff --git a/Src/Newtonsoft.Json/Linq/Extensions.cs b/Src/Newtonsoft.Json/Linq/Extensions.cs index e05fd262..cd333a2f 100644 --- a/Src/Newtonsoft.Json/Linq/Extensions.cs +++ b/Src/Newtonsoft.Json/Linq/Extensions.cs @@ -291,10 +291,10 @@ namespace Newtonsoft.Json.Linq #pragma warning restore CS8653 // A default expression introduces a null value for a type parameter. } - targetType = Nullable.GetUnderlyingType(targetType); + targetType = Nullable.GetUnderlyingType(targetType)!; } - return (U)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture); + return (U?)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture); } } diff --git a/Src/Newtonsoft.Json/Linq/JConstructor.cs b/Src/Newtonsoft.Json/Linq/JConstructor.cs index 4903c0a2..f2aa8618 100644 --- a/Src/Newtonsoft.Json/Linq/JConstructor.cs +++ b/Src/Newtonsoft.Json/Linq/JConstructor.cs @@ -202,7 +202,13 @@ namespace Newtonsoft.Json.Linq internal override int GetDeepHashCode() { - return (_name?.GetHashCode() ?? 0) ^ ContentsHashCode(); + int hash; +#if HAVE_GETHASHCODE_STRING_COMPARISON + hash = _name?.GetHashCode(StringComparison.Ordinal) ?? 0; +#else + hash = _name?.GetHashCode() ?? 0; +#endif + return hash ^ ContentsHashCode(); } /// diff --git a/Src/Newtonsoft.Json/Linq/JContainer.Async.cs b/Src/Newtonsoft.Json/Linq/JContainer.Async.cs index beb67afd..8c02b295 100644 --- a/Src/Newtonsoft.Json/Linq/JContainer.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JContainer.Async.cs @@ -109,7 +109,7 @@ namespace Newtonsoft.Json.Linq parent = parent.Parent; break; case JsonToken.StartConstructor: - JConstructor constructor = new JConstructor(reader.Value!.ToString()); + JConstructor constructor = new JConstructor(reader.Value!.ToString()!); constructor.SetLineInfo(lineInfo, settings); parent.Add(constructor); parent = constructor; diff --git a/Src/Newtonsoft.Json/Linq/JContainer.cs b/Src/Newtonsoft.Json/Linq/JContainer.cs index 07f833bd..f9447cd5 100644 --- a/Src/Newtonsoft.Json/Linq/JContainer.cs +++ b/Src/Newtonsoft.Json/Linq/JContainer.cs @@ -84,7 +84,7 @@ namespace Newtonsoft.Json.Linq /// /// Occurs when the items list of the collection has changed, or the collection is reset. /// - public event NotifyCollectionChangedEventHandler CollectionChanged + public event NotifyCollectionChangedEventHandler? CollectionChanged { add { _collectionChanged += value; } remove { _collectionChanged -= value; } @@ -839,7 +839,7 @@ namespace Newtonsoft.Json.Linq parent = parent.Parent; break; case JsonToken.StartConstructor: - JConstructor constructor = new JConstructor(r.Value!.ToString()); + JConstructor constructor = new JConstructor(r.Value!.ToString()!); constructor.SetLineInfo(lineInfo, settings); parent.Add(constructor); parent = constructor; @@ -902,7 +902,7 @@ namespace Newtonsoft.Json.Linq DuplicatePropertyNameHandling duplicatePropertyNameHandling = settings?.DuplicatePropertyNameHandling ?? DuplicatePropertyNameHandling.Replace; JObject parentObject = (JObject)parent; - string propertyName = r.Value!.ToString(); + string propertyName = r.Value!.ToString()!; JProperty? existingPropertyWithName = parentObject.Property(propertyName, StringComparison.Ordinal); if (existingPropertyWithName != null) { @@ -947,10 +947,11 @@ namespace Newtonsoft.Json.Linq return string.Empty; } - PropertyDescriptorCollection? ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) + PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { ICustomTypeDescriptor? d = First as ICustomTypeDescriptor; - return d?.GetProperties(); + + return d?.GetProperties() ?? new PropertyDescriptorCollection(CollectionUtils.ArrayEmpty()); } #endif @@ -1006,7 +1007,7 @@ namespace Newtonsoft.Json.Linq } #endregion - private JToken? EnsureValue(object value) + private JToken? EnsureValue(object? value) { if (value == null) { @@ -1022,7 +1023,7 @@ namespace Newtonsoft.Json.Linq } #region IList Members - int IList.Add(object value) + int IList.Add(object? value) { Add(EnsureValue(value)); return Count - 1; @@ -1033,17 +1034,17 @@ namespace Newtonsoft.Json.Linq ClearItems(); } - bool IList.Contains(object value) + bool IList.Contains(object? value) { return ContainsItem(EnsureValue(value)); } - int IList.IndexOf(object value) + int IList.IndexOf(object? value) { return IndexOfItem(EnsureValue(value)); } - void IList.Insert(int index, object value) + void IList.Insert(int index, object? value) { InsertItem(index, EnsureValue(value), false); } @@ -1052,7 +1053,7 @@ namespace Newtonsoft.Json.Linq bool IList.IsReadOnly => false; - void IList.Remove(object value) + void IList.Remove(object? value) { RemoveItem(EnsureValue(value)); } @@ -1062,7 +1063,7 @@ namespace Newtonsoft.Json.Linq RemoveItemAt(index); } - object IList.this[int index] + object? IList.this[int index] { get => GetItem(index); set => SetItem(index, EnsureValue(value)); diff --git a/Src/Newtonsoft.Json/Linq/JEnumerable.cs b/Src/Newtonsoft.Json/Linq/JEnumerable.cs index 541f1beb..41de4c33 100644 --- a/Src/Newtonsoft.Json/Linq/JEnumerable.cs +++ b/Src/Newtonsoft.Json/Linq/JEnumerable.cs @@ -111,7 +111,7 @@ namespace Newtonsoft.Json.Linq /// /// true if the specified is equal to this instance; otherwise, false. /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is JEnumerable enumerable) { diff --git a/Src/Newtonsoft.Json/Linq/JObject.Async.cs b/Src/Newtonsoft.Json/Linq/JObject.Async.cs index d973e8bc..67f01fe5 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.Async.cs @@ -45,7 +45,7 @@ namespace Newtonsoft.Json.Linq public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { Task t = writer.WriteStartObjectAsync(cancellationToken); - if (!t.IsCompletedSucessfully()) + if (!t.IsCompletedSuccessfully()) { return AwaitProperties(t, 0, writer, cancellationToken, converters); } @@ -53,7 +53,7 @@ namespace Newtonsoft.Json.Linq for (int i = 0; i < _properties.Count; i++) { t = _properties[i].WriteToAsync(writer, cancellationToken, converters); - if (!t.IsCompletedSucessfully()) + if (!t.IsCompletedSuccessfully()) { return AwaitProperties(t, i + 1, writer, cancellationToken, converters); } diff --git a/Src/Newtonsoft.Json/Linq/JObject.cs b/Src/Newtonsoft.Json/Linq/JObject.cs index 371a951f..872c8ae7 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.cs @@ -742,7 +742,7 @@ namespace Newtonsoft.Json.Linq return ((ICustomTypeDescriptor)this).GetProperties(null); } - PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) + PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes) { PropertyDescriptor[] propertiesArray = new PropertyDescriptor[Count]; int i = 0; @@ -790,7 +790,7 @@ namespace Newtonsoft.Json.Linq return null; } - EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) + EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[]? attributes) { return EventDescriptorCollection.Empty; } @@ -800,7 +800,7 @@ namespace Newtonsoft.Json.Linq return EventDescriptorCollection.Empty; } - object? ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) + object? ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor? pd) { if (pd is JPropertyDescriptor) { diff --git a/Src/Newtonsoft.Json/Linq/JProperty.Async.cs b/Src/Newtonsoft.Json/Linq/JProperty.Async.cs index dcd7cb3b..d1e845dc 100644 --- a/Src/Newtonsoft.Json/Linq/JProperty.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JProperty.Async.cs @@ -44,7 +44,7 @@ namespace Newtonsoft.Json.Linq public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { Task task = writer.WritePropertyNameAsync(_name, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return WriteValueAsync(writer, cancellationToken, converters); } diff --git a/Src/Newtonsoft.Json/Linq/JProperty.cs b/Src/Newtonsoft.Json/Linq/JProperty.cs index b59918d8..3c738cf5 100644 --- a/Src/Newtonsoft.Json/Linq/JProperty.cs +++ b/Src/Newtonsoft.Json/Linq/JProperty.cs @@ -353,7 +353,13 @@ namespace Newtonsoft.Json.Linq internal override int GetDeepHashCode() { - return _name.GetHashCode() ^ (Value?.GetDeepHashCode() ?? 0); + int hash; +#if HAVE_GETHASHCODE_STRING_COMPARISON + hash = _name.GetHashCode(StringComparison.Ordinal); +#else + hash = _name.GetHashCode(); +#endif + return hash ^ (Value?.GetDeepHashCode() ?? 0); } /// diff --git a/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs b/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs index 72ea0207..606b2f2d 100644 --- a/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs +++ b/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs @@ -67,7 +67,7 @@ namespace Newtonsoft.Json.Linq /// The value of a property for a given component. /// /// The component with the property for which to retrieve the value. - public override object? GetValue(object component) + public override object? GetValue(object? component) { return (component as JObject)?[Name]; } @@ -85,7 +85,7 @@ namespace Newtonsoft.Json.Linq /// /// The component with the property value that is to be set. /// The new value. - public override void SetValue(object component, object value) + public override void SetValue(object? component, object? value) { if (component is JObject o) { diff --git a/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs b/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs index 1c4c186b..42a37d8a 100644 --- a/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs +++ b/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs @@ -131,7 +131,7 @@ namespace Newtonsoft.Json.Linq if (_dictionary != null) { - return _dictionary.TryGetValue(key, out JToken value) && Remove(value); + return _dictionary.TryGetValue(key, out JToken? value) && Remove(value); } return false; @@ -259,7 +259,7 @@ namespace Newtonsoft.Json.Linq foreach (KeyValuePair keyAndProperty in d1) { - if (!d2.TryGetValue(keyAndProperty.Key, out JToken secondValue)) + if (!d2.TryGetValue(keyAndProperty.Key, out JToken? secondValue)) { return false; } diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 9cb008ae..336d748a 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -1333,7 +1333,7 @@ namespace Newtonsoft.Json.Linq if (v.Value is string) { - return Convert.FromBase64String(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return Convert.FromBase64String(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } #if HAVE_BIG_INTEGER if (v.Value is BigInteger integer) @@ -1368,7 +1368,7 @@ namespace Newtonsoft.Json.Linq return new Guid(bytes); } - return (v.Value is Guid guid) ? guid : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return (v.Value is Guid guid) ? guid : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } /// @@ -1399,7 +1399,7 @@ namespace Newtonsoft.Json.Linq return new Guid(bytes); } - return (v.Value is Guid guid) ? guid : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return (v.Value is Guid guid) ? guid : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } /// @@ -1415,7 +1415,7 @@ namespace Newtonsoft.Json.Linq throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); } - return (v.Value is TimeSpan span) ? span : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return (v.Value is TimeSpan span) ? span : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } /// @@ -1441,7 +1441,7 @@ namespace Newtonsoft.Json.Linq return null; } - return (v.Value is TimeSpan span) ? span : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return (v.Value is TimeSpan span) ? span : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } /// @@ -1467,7 +1467,7 @@ namespace Newtonsoft.Json.Linq return null; } - return (v.Value is Uri uri) ? uri : new Uri(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return (v.Value is Uri uri) ? uri : new Uri(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } #if HAVE_BIG_INTEGER @@ -1957,15 +1957,15 @@ namespace Newtonsoft.Json.Linq } catch (Exception ex) { - Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType); + Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType)!; throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string?)this, enumType.Name), ex); } } if (Type == JTokenType.Integer) { - Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType); - return Enum.ToObject(enumType, ((JValue)this).Value); + Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType)!; + return Enum.ToObject(enumType, ((JValue)this).Value!); } } diff --git a/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs b/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs index 2930896d..8e5314b2 100644 --- a/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs +++ b/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs @@ -40,7 +40,7 @@ namespace Newtonsoft.Json.Linq /// /// true if the specified objects are equal; otherwise, false. /// - public bool Equals(JToken x, JToken y) + public bool Equals(JToken? x, JToken? y) { return JToken.DeepEquals(x, y); } diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs index 86ea4dfe..09ed1fd4 100644 --- a/Src/Newtonsoft.Json/Linq/JValue.cs +++ b/Src/Newtonsoft.Json/Linq/JValue.cs @@ -307,8 +307,8 @@ namespace Newtonsoft.Json.Linq case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: - string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture); - string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture); + string? s1 = Convert.ToString(objA, CultureInfo.InvariantCulture); + string? s2 = Convert.ToString(objB, CultureInfo.InvariantCulture); return string.CompareOrdinal(s1, s2); case JTokenType.Boolean: @@ -859,7 +859,7 @@ namespace Newtonsoft.Json.Linq /// /// true if the specified is equal to the current ; otherwise, false. /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is JValue v) { @@ -902,7 +902,7 @@ namespace Newtonsoft.Json.Linq return string.Empty; } - return _value.ToString(); + return _value.ToString()!; } /// @@ -924,7 +924,7 @@ namespace Newtonsoft.Json.Linq /// /// A that represents this instance. /// - public string ToString(IFormatProvider formatProvider) + public string ToString(IFormatProvider? formatProvider) { return ToString(null, formatProvider); } @@ -937,7 +937,7 @@ namespace Newtonsoft.Json.Linq /// /// A that represents this instance. /// - public string ToString(string? format, IFormatProvider formatProvider) + public string ToString(string? format, IFormatProvider? formatProvider) { if (_value == null) { @@ -950,7 +950,7 @@ namespace Newtonsoft.Json.Linq } else { - return _value.ToString(); + return _value.ToString()!; } } @@ -1035,7 +1035,7 @@ namespace Newtonsoft.Json.Linq } #endif - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { if (obj == null) { @@ -1078,7 +1078,7 @@ namespace Newtonsoft.Json.Linq /// /// is not of the same type as this instance. /// - public int CompareTo(JValue obj) + public int CompareTo(JValue? obj) { if (obj == null) { @@ -1108,79 +1108,79 @@ namespace Newtonsoft.Json.Linq return TypeCode.Object; } - bool IConvertible.ToBoolean(IFormatProvider provider) + bool IConvertible.ToBoolean(IFormatProvider? provider) { return (bool)this; } - char IConvertible.ToChar(IFormatProvider provider) + char IConvertible.ToChar(IFormatProvider? provider) { return (char)this; } - sbyte IConvertible.ToSByte(IFormatProvider provider) + sbyte IConvertible.ToSByte(IFormatProvider? provider) { return (sbyte)this; } - byte IConvertible.ToByte(IFormatProvider provider) + byte IConvertible.ToByte(IFormatProvider? provider) { return (byte)this; } - short IConvertible.ToInt16(IFormatProvider provider) + short IConvertible.ToInt16(IFormatProvider? provider) { return (short)this; } - ushort IConvertible.ToUInt16(IFormatProvider provider) + ushort IConvertible.ToUInt16(IFormatProvider? provider) { return (ushort)this; } - int IConvertible.ToInt32(IFormatProvider provider) + int IConvertible.ToInt32(IFormatProvider? provider) { return (int)this; } - uint IConvertible.ToUInt32(IFormatProvider provider) + uint IConvertible.ToUInt32(IFormatProvider? provider) { return (uint)this; } - long IConvertible.ToInt64(IFormatProvider provider) + long IConvertible.ToInt64(IFormatProvider? provider) { return (long)this; } - ulong IConvertible.ToUInt64(IFormatProvider provider) + ulong IConvertible.ToUInt64(IFormatProvider? provider) { return (ulong)this; } - float IConvertible.ToSingle(IFormatProvider provider) + float IConvertible.ToSingle(IFormatProvider? provider) { return (float)this; } - double IConvertible.ToDouble(IFormatProvider provider) + double IConvertible.ToDouble(IFormatProvider? provider) { return (double)this; } - decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider? provider) { return (decimal)this; } - DateTime IConvertible.ToDateTime(IFormatProvider provider) + DateTime IConvertible.ToDateTime(IFormatProvider? provider) { return (DateTime)this; } - object? IConvertible.ToType(Type conversionType, IFormatProvider provider) + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) { - return ToObject(conversionType); + return ToObject(conversionType)!; } #endif } diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs b/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs index 1ab97041..617a7c41 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs @@ -291,7 +291,7 @@ namespace Newtonsoft.Json.Linq.JsonPath break; case JTokenType.Guid: case JTokenType.TimeSpan: - currentValueString = value.Value!.ToString(); + currentValueString = value.Value!.ToString()!; break; case JTokenType.Uri: currentValueString = ((Uri)value.Value!).OriginalString; diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index fd834d77..21b98b1e 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -1,6 +1,6 @@  - net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0 + net6.0;net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0 $(LibraryFrameworks) 9.0 @@ -51,8 +51,12 @@ + + Json.NET .NET 6.0 + HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;$(AdditionalConstants) + - Json.NET + Json.NET .NET 4.5 HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CAS;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;$(AdditionalConstants) diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs index 445d3a6f..b506565d 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs @@ -89,7 +89,10 @@ namespace Newtonsoft.Json.Schema private string UnescapeReference(string reference) { - return Uri.UnescapeDataString(reference).Replace("~1", "/").Replace("~0", "~"); + string unescapedReference = Uri.UnescapeDataString(reference); + unescapedReference = StringUtils.Replace(unescapedReference, "~1", "/"); + unescapedReference = StringUtils.Replace(unescapedReference, "~0", "~"); + return unescapedReference; } private JsonSchema ResolveReferences(JsonSchema schema) @@ -220,7 +223,11 @@ namespace Newtonsoft.Json.Schema return deferredSchema; } - string location = token.Path.Replace(".", "/").Replace("[", "/").Replace("]", string.Empty); + string location = token.Path; + location = StringUtils.Replace(location, ".", "/"); + location = StringUtils.Replace(location, "[", "/"); + location = StringUtils.Replace(location, "]", string.Empty); + if (!StringUtils.IsNullOrEmpty(location)) { location = "/" + location; diff --git a/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs b/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs index d3fdcf02..554e89a5 100644 --- a/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs @@ -66,7 +66,7 @@ namespace Newtonsoft.Json.Serialization // for backwards compadibility the CamelCasePropertyNamesContractResolver shares contracts between instances StructMultiKey key = new StructMultiKey(GetType(), type); Dictionary, JsonContract>? cache = _contractCache; - if (cache == null || !cache.TryGetValue(key, out JsonContract contract)) + if (cache == null || !cache.TryGetValue(key, out JsonContract? contract)) { contract = CreateContract(type); diff --git a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index 87a781b2..864697f0 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -418,7 +418,7 @@ namespace Newtonsoft.Json.Serialization } } - MemberInfo extensionDataMember = GetExtensionDataMemberForType(contract.NonNullableUnderlyingType); + MemberInfo? extensionDataMember = GetExtensionDataMemberForType(contract.NonNullableUnderlyingType); if (extensionDataMember != null) { SetExtensionDataDelegates(contract, extensionDataMember); @@ -439,7 +439,7 @@ namespace Newtonsoft.Json.Serialization throw new JsonSerializationException("Unable to serialize instance of '{0}'.".FormatWith(CultureInfo.InvariantCulture, o.GetType())); } - private MemberInfo GetExtensionDataMemberForType(Type type) + private MemberInfo? GetExtensionDataMemberForType(Type type) { IEnumerable members = GetClassHierarchyForType(type).SelectMany(baseType => { @@ -450,7 +450,7 @@ namespace Newtonsoft.Json.Serialization return m; }); - MemberInfo extensionDataMember = members.LastOrDefault(m => + MemberInfo? extensionDataMember = members.LastOrDefault(m => { MemberTypes memberType = m.MemberType(); if (memberType != MemberTypes.Property && memberType != MemberTypes.Field) @@ -466,7 +466,7 @@ namespace Newtonsoft.Json.Serialization if (!ReflectionUtils.CanReadMemberValue(m, true)) { - throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' must have a getter.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name)); + throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' must have a getter.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType!), m.Name)); } Type t = ReflectionUtils.GetMemberUnderlyingType(m); @@ -482,7 +482,7 @@ namespace Newtonsoft.Json.Serialization } } - throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name)); + throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType!), m.Name)); }); return extensionDataMember; @@ -640,7 +640,7 @@ namespace Newtonsoft.Json.Serialization { foreach (ParameterInfo parameterInfo in parameters) { - JsonProperty? memberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); + JsonProperty? memberProperty = MatchProperty(memberProperties, parameterInfo.Name!, parameterInfo.ParameterType); if (memberProperty == null || memberProperty.Writable) { return null; @@ -688,7 +688,7 @@ namespace Newtonsoft.Json.Serialization { ParameterInfo[] constructorParameters = constructor.GetParameters(); - JsonPropertyCollection parameterCollection = new JsonPropertyCollection(constructor.DeclaringType); + JsonPropertyCollection parameterCollection = new JsonPropertyCollection(constructor.DeclaringType!); foreach (ParameterInfo parameterInfo in constructorParameters) { @@ -746,7 +746,7 @@ namespace Newtonsoft.Json.Serialization property.PropertyType = parameterInfo.ParameterType; property.AttributeProvider = new ReflectionAttributeProvider(parameterInfo); - SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out _); + SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name!, parameterInfo.Member.DeclaringType!, MemberSerialization.OptOut, out _); property.Readable = false; property.Writable = true; @@ -989,7 +989,7 @@ namespace Newtonsoft.Json.Serialization { List ret = new List(); - Type current = type; + Type? current = type; while (current != null && current != typeof(object)) { ret.Add(current); @@ -1127,7 +1127,7 @@ namespace Newtonsoft.Json.Serialization if (contract.IsInstantiable) { - ConstructorInfo constructorInfo = contract.NonNullableUnderlyingType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] {typeof(SerializationInfo), typeof(StreamingContext)}, null); + ConstructorInfo? constructorInfo = contract.NonNullableUnderlyingType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] {typeof(SerializationInfo), typeof(StreamingContext)}, null); if (constructorInfo != null) { ObjectConstructor creator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructorInfo); @@ -1304,36 +1304,36 @@ namespace Newtonsoft.Json.Serialization if (currentCallback != null) { - throw new JsonException("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType)); + throw new JsonException("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType!), attributeType)); } if (prevAttributeType != null) { - throw new JsonException("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method)); + throw new JsonException("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType!), method)); } if (method.IsVirtual) { - throw new JsonException("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType)); + throw new JsonException("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType!), attributeType)); } if (method.ReturnType != typeof(void)) { - throw new JsonException("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method)); + throw new JsonException("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType!), method)); } if (attributeType == typeof(OnErrorAttribute)) { if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext)) { - throw new JsonException("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext), typeof(ErrorContext))); + throw new JsonException("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType!), method, typeof(StreamingContext), typeof(ErrorContext))); } } else { if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext)) { - throw new JsonException("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext))); + throw new JsonException("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType!), method, typeof(StreamingContext))); } } @@ -1346,7 +1346,7 @@ namespace Newtonsoft.Json.Serialization { if (type.IsGenericTypeDefinition() || !type.ContainsGenericParameters()) { - return type.FullName; + return type.FullName!; } return "{0}.{1}".FormatWith(CultureInfo.InvariantCulture, type.Namespace, type.Name); @@ -1437,7 +1437,7 @@ namespace Newtonsoft.Json.Serialization property.ValueProvider = CreateMemberValueProvider(member); property.AttributeProvider = new ReflectionAttributeProvider(member); - SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType, memberSerialization, out bool allowNonPublicAccess); + SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType!, memberSerialization, out bool allowNonPublicAccess); if (memberSerialization != MemberSerialization.Fields) { @@ -1635,7 +1635,7 @@ namespace Newtonsoft.Json.Serialization private Predicate? CreateShouldSerializeTest(MemberInfo member) { - MethodInfo shouldSerializeMethod = member.DeclaringType.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, ReflectionUtils.EmptyTypes); + MethodInfo? shouldSerializeMethod = member.DeclaringType!.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, ReflectionUtils.EmptyTypes); if (shouldSerializeMethod == null || shouldSerializeMethod.ReturnType != typeof(bool)) { @@ -1650,7 +1650,7 @@ namespace Newtonsoft.Json.Serialization private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess) { - MemberInfo? specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + MemberInfo? specifiedMember = member.DeclaringType!.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (specifiedMember == null) { specifiedMember = member.DeclaringType.GetField(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); diff --git a/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs index 83e0f484..e33dc58b 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs @@ -52,15 +52,15 @@ namespace Newtonsoft.Json.Serialization public object ResolveReference(object context, string reference) { - GetMappings(context).TryGetByFirst(reference, out object value); - return value; + GetMappings(context).TryGetByFirst(reference, out object? value); + return value!; } public string GetReference(object context, object value) { BidirectionalDictionary mappings = GetMappings(context); - if (!mappings.TryGetBySecond(value, out string reference)) + if (!mappings.TryGetBySecond(value, out string? reference)) { _referenceCount++; reference = _referenceCount.ToString(CultureInfo.InvariantCulture); diff --git a/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs b/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs index 1adf55a6..37d25cf2 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs @@ -60,7 +60,7 @@ namespace Newtonsoft.Json.Serialization if (assemblyName != null) { - Assembly assembly; + Assembly? assembly; #if !(DOTNET || PORTABLE40 || PORTABLE) // look, I don't like using obsolete methods as much as you do but this is the only way @@ -101,7 +101,7 @@ namespace Newtonsoft.Json.Serialization { // if generic type, try manually parsing the type arguments for the case of dynamically loaded assemblies // example generic typeName format: System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] - if (typeName.IndexOf('`') >= 0) + if (StringUtils.IndexOf(typeName, '`') >= 0) { try { @@ -123,18 +123,18 @@ namespace Newtonsoft.Json.Serialization } else { - return Type.GetType(typeName); + return Type.GetType(typeName)!; } } private Type? GetGenericTypeFromTypeName(string typeName, Assembly assembly) { Type? type = null; - int openBracketIndex = typeName.IndexOf('['); + int openBracketIndex = StringUtils.IndexOf(typeName, '['); if (openBracketIndex >= 0) { string genericTypeDefName = typeName.Substring(0, openBracketIndex); - Type genericTypeDef = assembly.GetType(genericTypeDefName); + Type? genericTypeDef = assembly.GetType(genericTypeDefName); if (genericTypeDef != null) { List genericTypeArguments = new List(); diff --git a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs index a2ce9dac..87c409e6 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs @@ -127,7 +127,7 @@ namespace Newtonsoft.Json.Serialization Type? tempCollectionType; if (IsArray) { - CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); + CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType)!; IsReadOnlyOrFixedSize = true; _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); @@ -274,6 +274,7 @@ namespace Newtonsoft.Json.Serialization if (_genericWrapperCreator == null) { MiscellaneousUtils.Assert(_genericCollectionDefinitionType != null); + MiscellaneousUtils.Assert(CollectionItemType != null); _genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType); @@ -289,7 +290,7 @@ namespace Newtonsoft.Json.Serialization constructorArgument = _genericCollectionDefinitionType; } - ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument }); + ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument })!; _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } diff --git a/Src/Newtonsoft.Json/Serialization/JsonContract.cs b/Src/Newtonsoft.Json/Serialization/JsonContract.cs index c7747029..d4f802cb 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonContract.cs @@ -248,7 +248,7 @@ namespace Newtonsoft.Json.Serialization IsNullable = ReflectionUtils.IsNullable(underlyingType); - NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; + NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType)! : underlyingType; _createdType = CreatedType = NonNullableUnderlyingType; diff --git a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs index 6c5afbe1..25828d13 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs @@ -223,9 +223,9 @@ namespace Newtonsoft.Json.Serialization { if (_genericWrapperCreator == null) { - _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType); + _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType!, DictionaryValueType!); - ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType! }); + ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType! })!; _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } diff --git a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs index 46992bc6..408a0297 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs @@ -53,10 +53,10 @@ namespace Newtonsoft.Json.Serialization ValidationUtils.ArgumentNotNull(value, nameof(value)); JValue v = (JValue)value; - return (T)System.Convert.ChangeType(v.Value, typeof(T), CultureInfo.InvariantCulture); + return (T)System.Convert.ChangeType(v.Value, typeof(T), CultureInfo.InvariantCulture)!; } - public object? Convert(object value, Type type) + public object Convert(object value, Type type) { ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -65,7 +65,7 @@ namespace Newtonsoft.Json.Serialization throw new ArgumentException("Value is not a JToken.", nameof(value)); } - return _reader.CreateISerializableItem(token, type, _contract, _member); + return _reader.CreateISerializableItem(token, type, _contract, _member)!; } public object Convert(object value, TypeCode typeCode) @@ -74,7 +74,7 @@ namespace Newtonsoft.Json.Serialization object? resolvedValue = (value is JValue v) ? v.Value : value; - return System.Convert.ChangeType(resolvedValue, typeCode, CultureInfo.InvariantCulture); + return System.Convert.ChangeType(resolvedValue, typeCode, CultureInfo.InvariantCulture)!; } public bool ToBoolean(object value) diff --git a/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs b/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs index 8b3d201c..684be0d3 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs @@ -145,7 +145,7 @@ namespace Newtonsoft.Json.Serialization return property; } - private bool TryGetValue(string key, [NotNullWhen(true)]out JsonProperty? item) + private bool TryGetProperty(string key, [NotNullWhen(true)]out JsonProperty? item) { if (Dictionary == null) { @@ -167,7 +167,7 @@ namespace Newtonsoft.Json.Serialization // KeyedCollection has an ordinal comparer if (comparisonType == StringComparison.Ordinal) { - if (TryGetValue(propertyName, out JsonProperty? property)) + if (TryGetProperty(propertyName, out JsonProperty? property)) { return property; } diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs index 8e76dc0f..1cdb0c5a 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs @@ -35,7 +35,7 @@ namespace Newtonsoft.Json.Serialization { private class ReferenceEqualsEqualityComparer : IEqualityComparer { - bool IEqualityComparer.Equals(object x, object y) + bool IEqualityComparer.Equals(object? x, object? y) { return ReferenceEquals(x, y); } diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index df77f51f..4ef652b6 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -332,7 +332,7 @@ namespace Newtonsoft.Json.Serialization return EnsureType(reader, s, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.StartConstructor: - string constructorName = reader.Value!.ToString(); + string constructorName = reader.Value!.ToString()!; return EnsureType(reader, constructorName, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.Null: @@ -692,7 +692,7 @@ namespace Newtonsoft.Json.Serialization if (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (propertyName.Length > 0 && propertyName[0] == '$') { @@ -702,7 +702,7 @@ namespace Newtonsoft.Json.Serialization do { - propertyName = reader.Value!.ToString(); + propertyName = reader.Value!.ToString()!; if (string.Equals(propertyName, JsonTypeReflector.RefPropertyName, StringComparison.Ordinal)) { @@ -740,7 +740,7 @@ namespace Newtonsoft.Json.Serialization else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); - string qualifiedTypeName = reader.Value!.ToString(); + string qualifiedTypeName = reader.Value!.ToString()!; ResolveTypeName(reader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName); @@ -898,7 +898,7 @@ namespace Newtonsoft.Json.Serialization } else if (arrayContract.IsArray) { - Array a = Array.CreateInstance(arrayContract.CollectionItemType, list.Count); + Array a = Array.CreateInstance(arrayContract.CollectionItemType!, list.Count); list.CopyTo(a, 0); list = a; } @@ -975,7 +975,7 @@ namespace Newtonsoft.Json.Serialization } if (ConvertUtils.IsInteger(primitiveContract.TypeCode)) { - return Enum.ToObject(contract.NonNullableUnderlyingType, value); + return Enum.ToObject(contract.NonNullableUnderlyingType, value!); } } else if (contract.NonNullableUnderlyingType == typeof(DateTime)) @@ -1384,7 +1384,7 @@ namespace Newtonsoft.Json.Serialization { case JsonToken.PropertyName: object keyValue = reader.Value!; - if (CheckPropertyName(reader, keyValue.ToString())) + if (CheckPropertyName(reader, keyValue.ToString()!)) { continue; } @@ -1399,7 +1399,7 @@ namespace Newtonsoft.Json.Serialization case PrimitiveTypeCode.DateTime: case PrimitiveTypeCode.DateTimeNullable: { - keyValue = DateTimeUtils.TryParseDateTime(keyValue.ToString(), reader.DateTimeZoneHandling, reader.DateFormatString, reader.Culture, out DateTime dt) + keyValue = DateTimeUtils.TryParseDateTime(keyValue.ToString()!, reader.DateTimeZoneHandling, reader.DateFormatString, reader.Culture, out DateTime dt) ? dt : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; break; @@ -1408,7 +1408,7 @@ namespace Newtonsoft.Json.Serialization case PrimitiveTypeCode.DateTimeOffset: case PrimitiveTypeCode.DateTimeOffsetNullable: { - keyValue = DateTimeUtils.TryParseDateTimeOffset(keyValue.ToString(), reader.DateFormatString, reader.Culture, out DateTimeOffset dt) + keyValue = DateTimeUtils.TryParseDateTimeOffset(keyValue.ToString()!, reader.DateFormatString, reader.Culture, out DateTimeOffset dt) ? dt : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; break; @@ -1416,7 +1416,7 @@ namespace Newtonsoft.Json.Serialization #endif default: keyValue = contract.KeyContract != null && contract.KeyContract.IsEnum - ? EnumUtils.ParseEnum(contract.KeyContract.NonNullableUnderlyingType, (Serializer._contractResolver as DefaultContractResolver)?.NamingStrategy, keyValue.ToString(), false) + ? EnumUtils.ParseEnum(contract.KeyContract.NonNullableUnderlyingType, (Serializer._contractResolver as DefaultContractResolver)?.NamingStrategy, keyValue.ToString()!, false) : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; break; } @@ -1752,7 +1752,7 @@ namespace Newtonsoft.Json.Serialization switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value!.ToString(); + string memberName = reader.Value!.ToString()!; if (!reader.Read()) { throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); @@ -1855,7 +1855,7 @@ namespace Newtonsoft.Json.Serialization switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value!.ToString(); + string memberName = reader.Value!.ToString()!; try { @@ -2207,7 +2207,7 @@ namespace Newtonsoft.Json.Serialization switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value!.ToString(); + string memberName = reader.Value!.ToString()!; CreatorPropertyContext creatorPropertyContext = new CreatorPropertyContext(memberName) { @@ -2356,7 +2356,7 @@ namespace Newtonsoft.Json.Serialization { case JsonToken.PropertyName: { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (CheckPropertyName(reader, propertyName)) { diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs index 675b5fed..4ea15838 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs @@ -399,7 +399,7 @@ namespace Newtonsoft.Json.Serialization #if HAVE_TYPE_DESCRIPTOR if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out TypeConverter converter)) { - s = converter.ConvertToInvariantString(value); + s = converter.ConvertToInvariantString(value)!; return true; } #endif @@ -414,7 +414,7 @@ namespace Newtonsoft.Json.Serialization if (value is Type t) { - s = t.AssemblyQualifiedName; + s = t.AssemblyQualifiedName!; return true; } @@ -778,7 +778,7 @@ namespace Newtonsoft.Json.Serialization if (isTopLevel) { - object value = values.GetValue(newIndices); + object value = values.GetValue(newIndices)!; try { @@ -879,7 +879,7 @@ namespace Newtonsoft.Json.Serialization if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member)) { writer.WritePropertyName(serializationEntry.Name); - WriteReference(writer, serializationEntry.Value); + WriteReference(writer, serializationEntry.Value!); } else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member)) { @@ -1176,7 +1176,7 @@ namespace Newtonsoft.Json.Serialization return enumName; } - return Convert.ToString(name, CultureInfo.InvariantCulture); + return Convert.ToString(name, CultureInfo.InvariantCulture)!; } } } @@ -1188,7 +1188,7 @@ namespace Newtonsoft.Json.Serialization else { escape = true; - return name.ToString(); + return name.ToString()!; } } diff --git a/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs b/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs index 28783b4c..da843007 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs @@ -33,6 +33,7 @@ using System.Security; using System.Security.Permissions; #endif using Newtonsoft.Json.Utilities; +using System.Runtime.CompilerServices; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else @@ -99,7 +100,7 @@ namespace Newtonsoft.Json.Serialization public static DataContractAttribute? GetDataContractAttribute(Type type) { // DataContractAttribute does not have inheritance - Type currentType = type; + Type? currentType = type; while (currentType != null) { @@ -132,11 +133,11 @@ namespace Newtonsoft.Json.Serialization { if (propertyInfo.IsVirtual()) { - Type currentType = propertyInfo.DeclaringType; + Type? currentType = propertyInfo.DeclaringType; while (result == null && currentType != null) { - PropertyInfo baseProperty = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(currentType, propertyInfo); + PropertyInfo? baseProperty = (PropertyInfo?)ReflectionUtils.GetMemberInfoFromType(currentType, propertyInfo); if (baseProperty != null && baseProperty.IsVirtual()) { result = CachedAttributeGetter.GetAttribute(baseProperty); @@ -248,7 +249,7 @@ namespace Newtonsoft.Json.Serialization return param.GetType(); }).ToArray(); - ConstructorInfo parameterizedConstructorInfo = type.GetConstructor(paramTypes); + ConstructorInfo? parameterizedConstructorInfo = type.GetConstructor(paramTypes); if (parameterizedConstructorInfo != null) { @@ -347,10 +348,10 @@ namespace Newtonsoft.Json.Serialization T? attribute; #if !(NET20 || DOTNET) - Type? metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType); + Type? metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType!); if (metadataType != null) { - MemberInfo metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo); + MemberInfo? metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo); if (metadataTypeMemberInfo != null) { @@ -373,7 +374,7 @@ namespace Newtonsoft.Json.Serialization { foreach (Type typeInterface in memberInfo.DeclaringType.GetInterfaces()) { - MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo); + MemberInfo? interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo); if (interfaceTypeMemberInfo != null) { @@ -459,7 +460,9 @@ namespace Newtonsoft.Json.Serialization { if (_dynamicCodeGeneration == null) { -#if HAVE_CAS +#if HAVE_DYNAMIC_CODE_COMPILED + _dynamicCodeGeneration = RuntimeFeature.IsDynamicCodeCompiled; +#elif HAVE_CAS try { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); diff --git a/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs b/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs index 88118844..7412531e 100644 --- a/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs +++ b/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs @@ -123,7 +123,7 @@ namespace Newtonsoft.Json.Serialization /// /// /// - public override bool Equals(object obj) => Equals(obj as NamingStrategy); + public override bool Equals(object? obj) => Equals(obj as NamingStrategy); /// /// Compare to another NamingStrategy diff --git a/Src/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs b/Src/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs index 6a960a3d..e5465af8 100644 --- a/Src/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs +++ b/Src/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs @@ -43,7 +43,7 @@ namespace Newtonsoft.Json.Serialization public Type BindToType(string? assemblyName, string typeName) { - return SerializationBinder.BindToType(assemblyName, typeName); + return SerializationBinder.BindToType(assemblyName!, typeName)!; } public void BindToName(Type serializedType, out string? assemblyName, out string? typeName) diff --git a/Src/Newtonsoft.Json/Utilities/AsyncUtils.cs b/Src/Newtonsoft.Json/Utilities/AsyncUtils.cs index e863e735..578b37de 100644 --- a/Src/Newtonsoft.Json/Utilities/AsyncUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/AsyncUtils.cs @@ -95,11 +95,11 @@ namespace Newtonsoft.Json.Utilities return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : reader.ReadAsync(buffer, index, count); } - public static bool IsCompletedSucessfully(this Task task) + public static bool IsCompletedSuccessfully(this Task task) { // IsCompletedSucessfully is the faster method, but only currently exposed on .NET Core 2.0 -#if NETCOREAPP2_0 - return task.IsCompletedSucessfully; +#if NETCOREAPP2_0_OR_GREATER + return task.IsCompletedSuccessfully; #else return task.Status == TaskStatus.RanToCompletion; #endif diff --git a/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs b/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs index c1dd16d1..887ee7f0 100644 --- a/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs +++ b/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs @@ -78,12 +78,12 @@ namespace Newtonsoft.Json.Utilities if (_leftOverBytesCount > 0) { - if(FulfillFromLeftover(buffer, index, ref count)) + if (FulfillFromLeftover(buffer, index, ref count)) { return; } - int num2 = Convert.ToBase64CharArray(_leftOverBytes, 0, 3, _charsLine, 0); + int num2 = Convert.ToBase64CharArray(_leftOverBytes!, 0, 3, _charsLine, 0); WriteChars(_charsLine, 0, num2); } @@ -145,7 +145,7 @@ namespace Newtonsoft.Json.Utilities { if (_leftOverBytesCount > 0) { - int count = Convert.ToBase64CharArray(_leftOverBytes, 0, _leftOverBytesCount, _charsLine, 0); + int count = Convert.ToBase64CharArray(_leftOverBytes!, 0, _leftOverBytesCount, _charsLine, 0); WriteChars(_charsLine, 0, count); _leftOverBytesCount = 0; } @@ -169,7 +169,7 @@ namespace Newtonsoft.Json.Utilities return; } - int num2 = Convert.ToBase64CharArray(_leftOverBytes, 0, 3, _charsLine, 0); + int num2 = Convert.ToBase64CharArray(_leftOverBytes!, 0, 3, _charsLine, 0); await WriteCharsAsync(_charsLine, 0, num2, cancellationToken).ConfigureAwait(false); } @@ -203,7 +203,7 @@ namespace Newtonsoft.Json.Utilities if (_leftOverBytesCount > 0) { - int count = Convert.ToBase64CharArray(_leftOverBytes, 0, _leftOverBytesCount, _charsLine, 0); + int count = Convert.ToBase64CharArray(_leftOverBytes!, 0, _leftOverBytesCount, _charsLine, 0); _leftOverBytesCount = 0; return WriteCharsAsync(_charsLine, 0, count, cancellationToken); } diff --git a/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs b/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs index 2f97c0b9..7ed826d3 100644 --- a/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs +++ b/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs @@ -25,11 +25,14 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace Newtonsoft.Json.Utilities { internal class BidirectionalDictionary + where TFirst : notnull + where TSecond : notnull { private readonly IDictionary _firstToSecond; private readonly IDictionary _secondToFirst; @@ -61,7 +64,7 @@ namespace Newtonsoft.Json.Utilities public void Set(TFirst first, TSecond second) { - if (_firstToSecond.TryGetValue(first, out TSecond existingSecond)) + if (_firstToSecond.TryGetValue(first, out TSecond? existingSecond)) { if (!existingSecond!.Equals(second)) { @@ -69,7 +72,7 @@ namespace Newtonsoft.Json.Utilities } } - if (_secondToFirst.TryGetValue(second, out TFirst existingFirst)) + if (_secondToFirst.TryGetValue(second, out TFirst? existingFirst)) { if (!existingFirst!.Equals(first)) { @@ -81,12 +84,12 @@ namespace Newtonsoft.Json.Utilities _secondToFirst.Add(second, first); } - public bool TryGetByFirst(TFirst first, out TSecond second) + public bool TryGetByFirst(TFirst first, [NotNullWhen(true)] out TSecond? second) { return _firstToSecond.TryGetValue(first, out second); } - public bool TryGetBySecond(TSecond second, out TFirst first) + public bool TryGetBySecond(TSecond second, [NotNullWhen(true)] out TFirst? first) { return _secondToFirst.TryGetValue(second, out first); } diff --git a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs index 85826a55..8b0a0125 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs @@ -289,7 +289,7 @@ namespace Newtonsoft.Json.Utilities break; } - object v = currentArray[0]; + object? v = currentArray[0]; if (v is IList list) { currentArray = list; @@ -341,11 +341,11 @@ namespace Newtonsoft.Json.Utilities int index = indices[i]; if (i == indices.Length - 1) { - return currentList[index]; + return currentList[index]!; } else { - currentList = (IList)currentList[index]; + currentList = (IList)currentList[index]!; } } return currentList; @@ -368,15 +368,21 @@ namespace Newtonsoft.Json.Utilities public static T[] ArrayEmpty() { +#if !HAS_ARRAY_EMPTY // Enumerable.Empty no longer returns an empty array in .NET Core 3.0 return EmptyArrayContainer.Empty; +#else + return Array.Empty(); +#endif } +#if !HAS_ARRAY_EMPTY private static class EmptyArrayContainer { #pragma warning disable CA1825 // Avoid zero-length array allocations. public static readonly T[] Empty = new T[0]; #pragma warning restore CA1825 // Avoid zero-length array allocations. } +#endif } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs index ebb79f23..482dad0c 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs @@ -168,7 +168,7 @@ namespace Newtonsoft.Json.Utilities public virtual IEnumerator GetEnumerator() { - return (_genericCollection ?? _list.Cast()).GetEnumerator(); + return (_genericCollection ?? _list!.Cast()).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() @@ -176,25 +176,25 @@ namespace Newtonsoft.Json.Utilities return ((IEnumerable)_genericCollection! ?? _list!).GetEnumerator(); } - int IList.Add(object value) + int IList.Add(object? value) { VerifyValueType(value); - Add((T)value); + Add((T)value!); return (Count - 1); } - bool IList.Contains(object value) + bool IList.Contains(object? value) { if (IsCompatibleObject(value)) { - return Contains((T)value); + return Contains((T)value!); } return false; } - int IList.IndexOf(object value) + int IList.IndexOf(object? value) { if (_genericCollection != null) { @@ -203,7 +203,7 @@ namespace Newtonsoft.Json.Utilities if (IsCompatibleObject(value)) { - return _list!.IndexOf((T)value); + return _list!.IndexOf((T)value!); } return -1; @@ -219,7 +219,7 @@ namespace Newtonsoft.Json.Utilities _list!.RemoveAt(index); } - void IList.Insert(int index, object value) + void IList.Insert(int index, object? value) { if (_genericCollection != null) { @@ -227,7 +227,7 @@ namespace Newtonsoft.Json.Utilities } VerifyValueType(value); - _list!.Insert(index, (T)value); + _list!.Insert(index, (T)value!); } bool IList.IsFixedSize @@ -246,15 +246,15 @@ namespace Newtonsoft.Json.Utilities } } - void IList.Remove(object value) + void IList.Remove(object? value) { if (IsCompatibleObject(value)) { - Remove((T)value); + Remove((T)value!); } } - object IList.this[int index] + object? IList.this[int index] { get { @@ -273,7 +273,7 @@ namespace Newtonsoft.Json.Utilities } VerifyValueType(value); - _list![index] = (T)value; + _list![index] = (T?)value; } } @@ -297,7 +297,7 @@ namespace Newtonsoft.Json.Utilities } } - private static void VerifyValueType(object value) + private static void VerifyValueType(object? value) { if (!IsCompatibleObject(value)) { @@ -305,7 +305,7 @@ namespace Newtonsoft.Json.Utilities } } - private static bool IsCompatibleObject(object value) + private static bool IsCompatibleObject(object? value) { if (!(value is T) && (value != null || (typeof(T).IsValueType() && !ReflectionUtils.IsNullableType(typeof(T))))) { diff --git a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs index 364088e2..9ce44964 100644 --- a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -215,7 +215,7 @@ namespace Newtonsoft.Json.Utilities // performance? if (ReflectionUtils.IsNullableType(t)) { - Type nonNullable = Nullable.GetUnderlyingType(t); + Type nonNullable = Nullable.GetUnderlyingType(t)!; if (nonNullable.IsEnum()) { Type nullableUnderlyingType = typeof(Nullable<>).MakeGenericType(Enum.GetUnderlyingType(nonNullable)); @@ -263,7 +263,7 @@ namespace Newtonsoft.Json.Utilities { Type initialType = t.Value1; Type targetType = t.Value2; - MethodInfo castMethodInfo = targetType.GetMethod("op_Implicit", new[] { initialType }) + MethodInfo? castMethodInfo = targetType.GetMethod("op_Implicit", new[] { initialType }) ?? targetType.GetMethod("op_Explicit", new[] { initialType }); if (castMethodInfo == null) @@ -414,7 +414,7 @@ namespace Newtonsoft.Json.Utilities if (ReflectionUtils.IsNullableType(targetType)) { - targetType = Nullable.GetUnderlyingType(targetType); + targetType = Nullable.GetUnderlyingType(targetType)!; } Type initialType = initialValue.GetType(); @@ -432,7 +432,7 @@ namespace Newtonsoft.Json.Utilities { if (initialValue is string) { - value = Enum.Parse(targetType, initialValue.ToString(), true); + value = Enum.Parse(targetType, initialValue.ToString()!, true); return ConvertResult.Success; } else if (IsInteger(initialValue)) diff --git a/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs b/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs index a92e2639..cf769393 100644 --- a/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs @@ -89,7 +89,7 @@ namespace Newtonsoft.Json.Utilities { if (_dictionary != null) { - _dictionary.Add(key, value); + _dictionary.Add(key!, value); } else if (_genericDictionary != null) { @@ -105,7 +105,7 @@ namespace Newtonsoft.Json.Utilities { if (_dictionary != null) { - return _dictionary.Contains(key); + return _dictionary.Contains(key!); } #if HAVE_READ_ONLY_COLLECTIONS else if (_readOnlyDictionary != null) @@ -144,9 +144,9 @@ namespace Newtonsoft.Json.Utilities { if (_dictionary != null) { - if (_dictionary.Contains(key)) + if (_dictionary.Contains(key!)) { - _dictionary.Remove(key); + _dictionary.Remove(key!); return true; } else @@ -172,7 +172,7 @@ namespace Newtonsoft.Json.Utilities { if (_dictionary != null) { - if (!_dictionary.Contains(key)) + if (!_dictionary.Contains(key!)) { #pragma warning disable CS8653 // A default expression introduces a null value for a type parameter. value = default; @@ -181,7 +181,7 @@ namespace Newtonsoft.Json.Utilities } else { - value = (TValue)_dictionary[key]; + value = (TValue)_dictionary[key!]!; return true; } } @@ -224,7 +224,7 @@ namespace Newtonsoft.Json.Utilities { if (_dictionary != null) { - return (TValue)_dictionary[key]; + return (TValue)_dictionary[key!]!; } #if HAVE_READ_ONLY_COLLECTIONS else if (_readOnlyDictionary != null) @@ -241,7 +241,7 @@ namespace Newtonsoft.Json.Utilities { if (_dictionary != null) { - _dictionary[key] = value; + _dictionary[key!] = value; } #if HAVE_READ_ONLY_COLLECTIONS else if (_readOnlyDictionary != null) @@ -321,7 +321,7 @@ namespace Newtonsoft.Json.Utilities while (e.MoveNext()) { DictionaryEntry entry = e.Entry; - array[arrayIndex++] = new KeyValuePair((TKey)entry.Key, (TValue)entry.Value); + array[arrayIndex++] = new KeyValuePair((TKey)entry.Key, (TValue)entry.Value!); } } finally @@ -387,13 +387,13 @@ namespace Newtonsoft.Json.Utilities { if (_dictionary != null) { - if (_dictionary.Contains(item.Key)) + if (_dictionary.Contains(item.Key!)) { - object value = _dictionary[item.Key]; + object? value = _dictionary[item.Key!]; if (Equals(value, item.Value)) { - _dictionary.Remove(item.Key); + _dictionary.Remove(item.Key!); return true; } else @@ -422,7 +422,7 @@ namespace Newtonsoft.Json.Utilities { if (_dictionary != null) { - return _dictionary.Cast().Select(de => new KeyValuePair((TKey)de.Key, (TValue)de.Value)).GetEnumerator(); + return _dictionary.Cast().Select(de => new KeyValuePair((TKey)de.Key, (TValue)de.Value!)).GetEnumerator(); } #if HAVE_READ_ONLY_COLLECTIONS else if (_readOnlyDictionary != null) @@ -441,7 +441,7 @@ namespace Newtonsoft.Json.Utilities return GetEnumerator(); } - void IDictionary.Add(object key, object value) + void IDictionary.Add(object key, object? value) { if (_dictionary != null) { @@ -455,7 +455,7 @@ namespace Newtonsoft.Json.Utilities #endif else { - GenericDictionary.Add((TKey)key, (TValue)value); + GenericDictionary.Add((TKey)key, (TValue)value!); } } @@ -517,9 +517,9 @@ namespace Newtonsoft.Json.Utilities public object Key => Entry.Key; - public object Value => Entry.Value; + public object? Value => Entry.Value; - public object Current => new DictionaryEntry(_e.Current.Key, _e.Current.Value); + public object Current => new DictionaryEntry(_e.Current.Key!, _e.Current.Value); public bool MoveNext() { diff --git a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs index 41286c31..a00cc2ce 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs @@ -37,7 +37,7 @@ namespace Newtonsoft.Json.Utilities private readonly DynamicProxy _proxy; internal DynamicProxyMetaObject(Expression expression, T value, DynamicProxy proxy) - : base(expression, BindingRestrictions.Empty, value) + : base(expression, BindingRestrictions.Empty, value!) { _proxy = proxy; } @@ -109,7 +109,7 @@ namespace Newtonsoft.Json.Utilities new GetBinderAdapter(binder), NoArgs, fallback(null), - e => binder.FallbackInvoke(e, args, null) + e => binder.FallbackInvoke(e!, args, null) ), null ); @@ -197,7 +197,7 @@ namespace Newtonsoft.Json.Utilities Type t = binder.GetType(); while (!t.IsVisible()) { - t = t.BaseType(); + t = t.BaseType()!; } return Expression.Constant(binder, t); } @@ -256,7 +256,7 @@ namespace Newtonsoft.Json.Utilities Expression.Condition( Expression.Call( Expression.Constant(_proxy), - typeof(DynamicProxy).GetMethod(methodName), + typeof(DynamicProxy).GetMethod(methodName)!, callArgs ), resultMetaObject.Expression, @@ -304,7 +304,7 @@ namespace Newtonsoft.Json.Utilities Expression.Condition( Expression.Call( Expression.Constant(_proxy), - typeof(DynamicProxy).GetMethod(methodName), + typeof(DynamicProxy).GetMethod(methodName)!, callArgs ), result, @@ -342,7 +342,7 @@ namespace Newtonsoft.Json.Utilities Expression.Condition( Expression.Call( Expression.Constant(_proxy), - typeof(DynamicProxy).GetMethod(methodName), + typeof(DynamicProxy).GetMethod(methodName)!, callArgs ), Expression.Empty(), @@ -366,7 +366,7 @@ namespace Newtonsoft.Json.Utilities public override IEnumerable GetDynamicMemberNames() { - return _proxy.GetDynamicMemberNames((T)Value); + return _proxy.GetDynamicMemberNames((T)Value!); } // It is okay to throw NotSupported from this binder. This object @@ -380,7 +380,7 @@ namespace Newtonsoft.Json.Utilities { } - public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) + public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject? errorSuggestion) { throw new NotSupportedException(); } diff --git a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs index e899c4c3..10b4acb3 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs @@ -51,7 +51,7 @@ namespace Newtonsoft.Json.Utilities public override ObjectConstructor CreateParameterizedConstructor(MethodBase method) { - DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object[]) }, method.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString()!, typeof(object), new[] { typeof(object[]) }, method.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateMethodCallIL(method, generator, 0); @@ -61,7 +61,7 @@ namespace Newtonsoft.Json.Utilities public override MethodCall CreateMethodCall(MethodBase method) { - DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString()!, typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateMethodCallIL(method, generator, 1); @@ -80,14 +80,14 @@ namespace Newtonsoft.Json.Utilities generator.Emit(OpCodes.Ldlen); generator.Emit(OpCodes.Ldc_I4, args.Length); generator.Emit(OpCodes.Beq, argsOk); - generator.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(ReflectionUtils.EmptyTypes)); + generator.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(ReflectionUtils.EmptyTypes)!); generator.Emit(OpCodes.Throw); generator.MarkLabel(argsOk); if (!method.IsConstructor && !method.IsStatic) { - generator.PushInstance(method.DeclaringType); + generator.PushInstance(method.DeclaringType!); } LocalBuilder localConvertible = generator.DeclareLocal(typeof(IConvertible)); @@ -103,7 +103,7 @@ namespace Newtonsoft.Json.Utilities if (parameterType.IsByRef) { - parameterType = parameterType.GetElementType(); + parameterType = parameterType.GetElementType()!; LocalBuilder localVariable = generator.DeclareLocal(parameterType); @@ -170,7 +170,7 @@ namespace Newtonsoft.Json.Utilities if (parameterType.IsPrimitive()) { // for primitive types we need to handle type widening (e.g. short -> int) - MethodInfo toParameterTypeMethod = typeof(IConvertible) + MethodInfo? toParameterTypeMethod = typeof(IConvertible) .GetMethod("To" + parameterType.Name, new[] { typeof(IFormatProvider) }); if (toParameterTypeMethod != null) @@ -227,7 +227,7 @@ namespace Newtonsoft.Json.Utilities } Type returnType = method.IsConstructor - ? method.DeclaringType + ? method.DeclaringType! : ((MethodInfo)method).ReturnType; if (returnType != typeof(void)) @@ -268,7 +268,7 @@ namespace Newtonsoft.Json.Utilities } else { - ConstructorInfo constructorInfo = + ConstructorInfo? constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, ReflectionUtils.EmptyTypes, null); if (constructorInfo == null) @@ -284,7 +284,7 @@ namespace Newtonsoft.Json.Utilities public override Func CreateGet(PropertyInfo propertyInfo) { - DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(object), new[] { typeof(T) }, propertyInfo.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(object), new[] { typeof(T) }, propertyInfo.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateGetPropertyIL(propertyInfo, generator); @@ -294,7 +294,7 @@ namespace Newtonsoft.Json.Utilities private void GenerateCreateGetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) { - MethodInfo getMethod = propertyInfo.GetGetMethod(true); + MethodInfo? getMethod = propertyInfo.GetGetMethod(true); if (getMethod == null) { throw new ArgumentException("Property '{0}' does not have a getter.".FormatWith(CultureInfo.InvariantCulture, propertyInfo.Name)); @@ -302,7 +302,7 @@ namespace Newtonsoft.Json.Utilities if (!getMethod.IsStatic) { - generator.PushInstance(propertyInfo.DeclaringType); + generator.PushInstance(propertyInfo.DeclaringType!); } generator.CallMethod(getMethod); @@ -314,12 +314,12 @@ namespace Newtonsoft.Json.Utilities { if (fieldInfo.IsLiteral) { - object constantValue = fieldInfo.GetValue(null); + object constantValue = fieldInfo.GetValue(null)!; Func getter = o => constantValue; return getter; } - DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + fieldInfo.Name, typeof(T), new[] { typeof(object) }, fieldInfo.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + fieldInfo.Name, typeof(T), new[] { typeof(object) }, fieldInfo.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateGetFieldIL(fieldInfo, generator); @@ -331,7 +331,7 @@ namespace Newtonsoft.Json.Utilities { if (!fieldInfo.IsStatic) { - generator.PushInstance(fieldInfo.DeclaringType); + generator.PushInstance(fieldInfo.DeclaringType!); generator.Emit(OpCodes.Ldfld, fieldInfo); } else @@ -345,7 +345,7 @@ namespace Newtonsoft.Json.Utilities public override Action CreateSet(FieldInfo fieldInfo) { - DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateSetFieldIL(fieldInfo, generator); @@ -357,7 +357,7 @@ namespace Newtonsoft.Json.Utilities { if (!fieldInfo.IsStatic) { - generator.PushInstance(fieldInfo.DeclaringType); + generator.PushInstance(fieldInfo.DeclaringType!); } generator.Emit(OpCodes.Ldarg_1); @@ -377,7 +377,7 @@ namespace Newtonsoft.Json.Utilities public override Action CreateSet(PropertyInfo propertyInfo) { - DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateSetPropertyIL(propertyInfo, generator); @@ -387,10 +387,10 @@ namespace Newtonsoft.Json.Utilities internal static void GenerateCreateSetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) { - MethodInfo setMethod = propertyInfo.GetSetMethod(true); + MethodInfo setMethod = propertyInfo.GetSetMethod(true)!; if (!setMethod.IsStatic) { - generator.PushInstance(propertyInfo.DeclaringType); + generator.PushInstance(propertyInfo.DeclaringType!); } generator.Emit(OpCodes.Ldarg_1); diff --git a/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs b/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs index acb3e3a3..51aa7413 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs @@ -64,7 +64,7 @@ namespace Newtonsoft.Json.Utilities { if (!_init) { - Type binderType = Type.GetType(BinderTypeName, false); + Type? binderType = Type.GetType(BinderTypeName, false); if (binderType == null) { throw new InvalidOperationException("Could not resolve type '{0}'. You may need to add a reference to Microsoft.CSharp.dll to work with dynamic types.".FormatWith(CultureInfo.InvariantCulture, BinderTypeName)); @@ -82,15 +82,15 @@ namespace Newtonsoft.Json.Utilities private static object CreateSharpArgumentInfoArray(params int[] values) { - Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName); - Type csharpArgumentInfoFlags = Type.GetType(CSharpArgumentInfoFlagsTypeName); + Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!; + Type csharpArgumentInfoFlags = Type.GetType(CSharpArgumentInfoFlagsTypeName, true)!; Array a = Array.CreateInstance(csharpArgumentInfoType, values.Length); for (int i = 0; i < values.Length; i++) { - MethodInfo createArgumentInfoMethod = csharpArgumentInfoType.GetMethod("Create", new[] { csharpArgumentInfoFlags, typeof(string) }); - object arg = createArgumentInfoMethod.Invoke(null, new object?[] { 0, null }); + MethodInfo createArgumentInfoMethod = csharpArgumentInfoType.GetMethod("Create", new[] { csharpArgumentInfoFlags, typeof(string) })!; + object arg = createArgumentInfoMethod.Invoke(null, new object?[] { 0, null })!; a.SetValue(arg, i); } @@ -99,16 +99,16 @@ namespace Newtonsoft.Json.Utilities private static void CreateMemberCalls() { - Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true); - Type csharpBinderFlagsType = Type.GetType(CSharpBinderFlagsTypeName, true); - Type binderType = Type.GetType(BinderTypeName, true); + Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!; + Type csharpBinderFlagsType = Type.GetType(CSharpBinderFlagsTypeName, true)!; + Type binderType = Type.GetType(BinderTypeName, true)!; Type csharpArgumentInfoTypeEnumerableType = typeof(IEnumerable<>).MakeGenericType(csharpArgumentInfoType); - MethodInfo getMemberMethod = binderType.GetMethod("GetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }); + MethodInfo getMemberMethod = binderType.GetMethod("GetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType })!; _getMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getMemberMethod); - MethodInfo setMemberMethod = binderType.GetMethod("SetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }); + MethodInfo setMemberMethod = binderType.GetMethod("SetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType })!; _setMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(setMemberMethod); } #endif @@ -161,7 +161,7 @@ namespace Newtonsoft.Json.Utilities _innerBinder = innerBinder; } - public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) + public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject? errorSuggestion) { DynamicMetaObject retMetaObject = _innerBinder.Bind(target, CollectionUtils.ArrayEmpty()); @@ -183,7 +183,7 @@ namespace Newtonsoft.Json.Utilities _innerBinder = innerBinder; } - public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject errorSuggestion) + public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject? errorSuggestion) { DynamicMetaObject retMetaObject = _innerBinder.Bind(target, new DynamicMetaObject[] { value }); diff --git a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs index ea6d4530..a1b3bae9 100644 --- a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs @@ -60,11 +60,11 @@ namespace Newtonsoft.Json.Utilities { string name = names[i]; FieldInfo f = enumType.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; - values[i] = ToUInt64(f.GetValue(null)); + values[i] = ToUInt64(f.GetValue(null)!); string resolvedName; #if HAVE_DATA_CONTRACTS - string specifiedName = f.GetCustomAttributes(typeof(EnumMemberAttribute), true) + string? specifiedName = f.GetCustomAttributes(typeof(EnumMemberAttribute), true) .Cast() .Select(a => a.Value) .SingleOrDefault(); diff --git a/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs index 53a97eca..36acc7c0 100644 --- a/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs @@ -111,7 +111,7 @@ namespace Newtonsoft.Json.Utilities bool isByRef = false; if (parameterType.IsByRef) { - parameterType = parameterType.GetElementType(); + parameterType = parameterType.GetElementType()!; isByRef = true; } @@ -144,7 +144,7 @@ namespace Newtonsoft.Json.Utilities } else { - Expression readParameter = EnsureCastExpression(targetParameterExpression!, method.DeclaringType); + Expression readParameter = EnsureCastExpression(targetParameterExpression!, method.DeclaringType!); callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression); } @@ -194,7 +194,7 @@ namespace Newtonsoft.Json.Utilities // avoid error from expressions compiler because of abstract class if (type.IsAbstract()) { - return () => (T)Activator.CreateInstance(type); + return () => (T)Activator.CreateInstance(type)!; } try @@ -214,7 +214,7 @@ namespace Newtonsoft.Json.Utilities { // an error can be thrown if constructor is not valid on Win8 // will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag - return () => (T)Activator.CreateInstance(type); + return () => (T)Activator.CreateInstance(type)!; } } @@ -240,7 +240,7 @@ namespace Newtonsoft.Json.Utilities } else { - Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType); + Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType!); resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo); } @@ -266,7 +266,7 @@ namespace Newtonsoft.Json.Utilities } else { - Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType); + Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType!); fieldExpression = Expression.Field(sourceExpression, fieldInfo); } @@ -283,7 +283,7 @@ namespace Newtonsoft.Json.Utilities // use reflection for structs // expression doesn't correctly set value - if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly) + if (fieldInfo.DeclaringType!.IsValueType() || fieldInfo.IsInitOnly) { return LateBoundReflectionDelegateFactory.Instance.CreateSet(fieldInfo); } @@ -298,7 +298,7 @@ namespace Newtonsoft.Json.Utilities } else { - Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType); + Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType!); fieldExpression = Expression.Field(sourceExpression, fieldInfo); } @@ -319,7 +319,7 @@ namespace Newtonsoft.Json.Utilities // use reflection for structs // expression doesn't correctly set value - if (propertyInfo.DeclaringType.IsValueType()) + if (propertyInfo.DeclaringType!.IsValueType()) { return LateBoundReflectionDelegateFactory.Instance.CreateSet(propertyInfo); } @@ -345,7 +345,7 @@ namespace Newtonsoft.Json.Utilities } else { - Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType); + Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType!); setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter); } @@ -372,7 +372,7 @@ namespace Newtonsoft.Json.Utilities if (allowWidening && targetType.IsPrimitive()) { - MethodInfo toTargetTypeMethod = typeof(Convert) + MethodInfo? toTargetTypeMethod = typeof(Convert) .GetMethod("To" + targetType.Name, new[] { typeof(object) }); if (toTargetTypeMethod != null) diff --git a/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs b/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs index cb816660..925219ff 100644 --- a/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs @@ -60,7 +60,7 @@ namespace Newtonsoft.Json.Utilities { FSharpCoreAssembly = fsharpCoreAssembly; - Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType"); + Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType")!; MethodInfo isUnionMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "IsUnion", BindingFlags.Public | BindingFlags.Static); IsUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(isUnionMethodInfo)!; @@ -68,23 +68,23 @@ namespace Newtonsoft.Json.Utilities MethodInfo getUnionCasesMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "GetUnionCases", BindingFlags.Public | BindingFlags.Static); GetUnionCases = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getUnionCasesMethodInfo)!; - Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue"); + Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue")!; PreComputeUnionTagReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionTagReader"); PreComputeUnionReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionReader"); PreComputeUnionConstructor = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionConstructor"); - Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo"); + Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo")!; GetUnionCaseInfoName = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Name")!)!; GetUnionCaseInfoTag = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Tag")!)!; GetUnionCaseInfoDeclaringType = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("DeclaringType")!)!; - GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(unionCaseInfo.GetMethod("GetFields")); + GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(unionCaseInfo.GetMethod("GetFields")!); - Type listModule = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.ListModule"); - _ofSeq = listModule.GetMethod("OfSeq"); + Type listModule = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.ListModule")!; + _ofSeq = listModule.GetMethod("OfSeq")!; - _mapType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpMap`2"); + _mapType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpMap`2")!; } private static readonly object Lock = new object(); @@ -133,7 +133,7 @@ namespace Newtonsoft.Json.Utilities private static MethodInfo GetMethodWithNonPublicFallback(Type type, string methodName, BindingFlags bindingFlags) { - MethodInfo methodInfo = type.GetMethod(methodName, bindingFlags); + MethodInfo methodInfo = type.GetMethod(methodName, bindingFlags)!; // if no matching method then attempt to find with nonpublic flag // this is required because in WinApps some methods are private but always using NonPublic breaks medium trust @@ -141,7 +141,7 @@ namespace Newtonsoft.Json.Utilities // https://github.com/JamesNK/Newtonsoft.Json/issues/821 if (methodInfo == null && (bindingFlags & BindingFlags.NonPublic) != BindingFlags.NonPublic) { - methodInfo = type.GetMethod(methodName, bindingFlags | BindingFlags.NonPublic); + methodInfo = type.GetMethod(methodName, bindingFlags | BindingFlags.NonPublic)!; } return methodInfo!; @@ -150,7 +150,7 @@ namespace Newtonsoft.Json.Utilities private static MethodCall CreateFSharpFuncCall(Type type, string methodName) { MethodInfo innerMethodInfo = GetMethodWithNonPublicFallback(type, methodName, BindingFlags.Public | BindingFlags.Static); - MethodInfo invokeFunc = innerMethodInfo.ReturnType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance); + MethodInfo invokeFunc = innerMethodInfo.ReturnType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance)!; MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(innerMethodInfo); MethodCall invoke = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(invokeFunc)!; @@ -175,17 +175,17 @@ namespace Newtonsoft.Json.Utilities public ObjectConstructor CreateMap(Type keyType, Type valueType) { - MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator"); + MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator")!; MethodInfo creatorGeneric = creatorDefinition.MakeGenericMethod(keyType, valueType); - return (ObjectConstructor)creatorGeneric.Invoke(this, null); + return (ObjectConstructor)creatorGeneric.Invoke(this, null)!; } public ObjectConstructor BuildMapCreator() { Type genericMapType = _mapType.MakeGenericType(typeof(TKey), typeof(TValue)); - ConstructorInfo ctor = genericMapType.GetConstructor(new[] { typeof(IEnumerable>) }); + ConstructorInfo ctor = genericMapType.GetConstructor(new[] { typeof(IEnumerable>) })!; ObjectConstructor ctorDelegate = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(ctor); ObjectConstructor creator = args => diff --git a/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs b/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs index dfe5d45e..8d7ba74d 100644 --- a/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs @@ -116,17 +116,17 @@ namespace Newtonsoft.Json.Utilities if (underlyingType.IsGenericType()) { Type underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition(); - string name = underlyingTypeDefinition.FullName; + string name = underlyingTypeDefinition.FullName!; - ImmutableCollectionTypeInfo definition = ArrayContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); + ImmutableCollectionTypeInfo? definition = ArrayContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); if (definition != null) { - Type createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); - Type builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); + Type? createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); + Type? builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); if (createdTypeDefinition != null && builderTypeDefinition != null) { - MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => m.Name == "CreateRange" && m.GetParameters().Length == 1); + MethodInfo? mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => m.Name == "CreateRange" && m.GetParameters().Length == 1); if (mb != null) { createdType = createdTypeDefinition.MakeGenericType(collectionItemType); @@ -148,17 +148,17 @@ namespace Newtonsoft.Json.Utilities if (underlyingType.IsGenericType()) { Type underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition(); - string name = underlyingTypeDefinition.FullName; + string name = underlyingTypeDefinition.FullName!; - ImmutableCollectionTypeInfo definition = DictionaryContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); + ImmutableCollectionTypeInfo? definition = DictionaryContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); if (definition != null) { - Type createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); - Type builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); + Type? createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); + Type? builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); if (createdTypeDefinition != null && builderTypeDefinition != null) { - MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => + MethodInfo? mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => { ParameterInfo[] parameters = m.GetParameters(); diff --git a/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs b/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs index 9619e699..74695ed5 100644 --- a/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs @@ -289,6 +289,7 @@ namespace Newtonsoft.Json.Utilities } else { + MiscellaneousUtils.Assert(writeBuffer != null); writer.Write(writeBuffer, 0, UnicodeTextLength); } } @@ -386,7 +387,7 @@ namespace Newtonsoft.Json.Utilities bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { Task task = writer.WriteAsync(delimiter, cancellationToken); - if (!task.IsCompletedSucessfully()) + if (!task.IsCompletedSuccessfully()) { return WriteEscapedJavaScriptStringWithDelimitersAsync(task, writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } @@ -394,7 +395,7 @@ namespace Newtonsoft.Json.Utilities if (!StringUtils.IsNullOrEmpty(s)) { task = WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return writer.WriteAsync(delimiter, cancellationToken); } diff --git a/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs index 277f1ebb..67526268 100644 --- a/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs @@ -50,7 +50,7 @@ namespace Newtonsoft.Json.Utilities return a => c.Invoke(a); } - return a => method.Invoke(null, a); + return a => method.Invoke(null, a)!; } public override MethodCall CreateMethodCall(MethodBase method) @@ -71,10 +71,14 @@ namespace Newtonsoft.Json.Utilities if (type.IsValueType()) { - return () => (T)Activator.CreateInstance(type); + return () => (T)Activator.CreateInstance(type)!; } - ConstructorInfo constructorInfo = ReflectionUtils.GetDefaultConstructor(type, true); + ConstructorInfo? constructorInfo = ReflectionUtils.GetDefaultConstructor(type, true); + if (constructorInfo == null) + { + throw new InvalidOperationException("Unable to find default constructor for " + type.FullName); + } return () => (T)constructorInfo.Invoke(null); } diff --git a/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs b/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs index 137ec445..c469ce64 100644 --- a/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs @@ -92,7 +92,7 @@ namespace Newtonsoft.Json.Utilities return "{null}"; } - return (value is string s) ? @"""" + s + @"""" : value!.ToString(); + return (value is string s) ? @"""" + s + @"""" : value!.ToString()!; } public static int ByteArrayCompare(byte[] a1, byte[] a2) @@ -131,7 +131,7 @@ namespace Newtonsoft.Json.Utilities public static void GetQualifiedNameParts(string qualifiedName, out string? prefix, out string localName) { - int colonPosition = qualifiedName.IndexOf(':'); + int colonPosition = StringUtils.IndexOf(qualifiedName, ':'); if ((colonPosition == -1 || colonPosition == 0) || (qualifiedName.Length - 1) == colonPosition) { diff --git a/Src/Newtonsoft.Json/Utilities/NullableAttributes.cs b/Src/Newtonsoft.Json/Utilities/NullableAttributes.cs index fa1f55e9..5733cb80 100644 --- a/Src/Newtonsoft.Json/Utilities/NullableAttributes.cs +++ b/Src/Newtonsoft.Json/Utilities/NullableAttributes.cs @@ -23,6 +23,8 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion +#if !HAVE_NULLABLE_ATTRIBUTES + namespace System.Diagnostics.CodeAnalysis { /// Specifies that an output will not be null even if the corresponding type allows it. @@ -71,4 +73,6 @@ namespace System.Diagnostics.CodeAnalysis /// Gets the condition parameter value. public bool ParameterValue { get; } } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs index fd3cbaea..f3d59424 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -177,7 +177,7 @@ namespace Newtonsoft.Json.Utilities return typeName + (assemblyName == null ? "" : ", " + assemblyName); } - return t.AssemblyQualifiedName; + return t.AssemblyQualifiedName!; } private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) @@ -245,12 +245,12 @@ namespace Newtonsoft.Json.Utilities return (GetDefaultConstructor(t, nonPublic) != null); } - public static ConstructorInfo GetDefaultConstructor(Type t) + public static ConstructorInfo? GetDefaultConstructor(Type t) { return GetDefaultConstructor(t, false); } - public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic) + public static ConstructorInfo? GetDefaultConstructor(Type t, bool nonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (nonPublic) @@ -283,14 +283,14 @@ namespace Newtonsoft.Json.Utilities public static Type EnsureNotNullableType(Type t) { return (IsNullableType(t)) - ? Nullable.GetUnderlyingType(t) + ? Nullable.GetUnderlyingType(t)! : t; } public static Type EnsureNotByRefType(Type t) { return (t.IsByRef && t.HasElementType) - ? t.GetElementType() + ? t.GetElementType()! : t; } @@ -370,8 +370,9 @@ namespace Newtonsoft.Json.Utilities return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } - private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type? implementingType) + private static bool InheritsGenericDefinitionInternal(Type type, Type genericClassDefinition, out Type? implementingType) { + Type? currentType = type; do { if (currentType.IsGenericType() && genericClassDefinition == currentType.GetGenericTypeDefinition()) @@ -461,7 +462,7 @@ namespace Newtonsoft.Json.Utilities case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; case MemberTypes.Event: - return ((EventInfo)member).EventHandlerType; + return ((EventInfo)member).EventHandlerType!; case MemberTypes.Method: return ((MethodInfo)member).ReturnType; default: @@ -509,7 +510,7 @@ namespace Newtonsoft.Json.Utilities /// The member. /// The target object. /// The member's value on the object. - public static object GetMemberValue(MemberInfo member, object target) + public static object? GetMemberValue(MemberInfo member, object target) { ValidationUtils.ArgumentNotNull(member, nameof(member)); ValidationUtils.ArgumentNotNull(target, nameof(target)); @@ -713,7 +714,7 @@ namespace Newtonsoft.Json.Utilities return false; } - Type declaringType = propertyInfo.DeclaringType; + Type declaringType = propertyInfo.DeclaringType!; if (!declaringType.IsGenericType()) { return false; @@ -884,7 +885,7 @@ namespace Newtonsoft.Json.Utilities return null; } - public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) + public static MemberInfo? GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) { const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; @@ -916,8 +917,10 @@ namespace Newtonsoft.Json.Utilities } #if !PORTABLE - private static void GetChildPrivateFields(IList initialFields, Type targetType, BindingFlags bindingAttr) + private static void GetChildPrivateFields(IList initialFields, Type type, BindingFlags bindingAttr) { + Type? targetType = type; + // fix weirdness with private FieldInfos only being returned for the current Type // find base type fields and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) @@ -960,7 +963,7 @@ namespace Newtonsoft.Json.Utilities PropertyInfo member = propertyInfos[i]; if (member.DeclaringType != targetType) { - PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member); + PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType!, member)!; propertyInfos[i] = declaredMember; } } @@ -975,13 +978,14 @@ namespace Newtonsoft.Json.Utilities : bindingAttr; } - private static void GetChildPrivateProperties(IList initialProperties, Type targetType, BindingFlags bindingAttr) + private static void GetChildPrivateProperties(IList initialProperties, Type type, BindingFlags bindingAttr) { // fix weirdness with private PropertyInfos only being returned for the current Type // find base type properties and add them to result // also find base properties that have been hidden by subtype properties with the same name + Type? targetType = type; while ((targetType = targetType.BaseType()) != null) { foreach (PropertyInfo propertyInfo in targetType.GetProperties(bindingAttr)) @@ -1025,11 +1029,11 @@ namespace Newtonsoft.Json.Utilities } else { - Type subTypePropertyDeclaringType = subTypeProperty.GetBaseDefinition()?.DeclaringType ?? subTypeProperty.DeclaringType; + Type subTypePropertyDeclaringType = subTypeProperty.GetBaseDefinition()?.DeclaringType ?? subTypeProperty.DeclaringType!; int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name && p.IsVirtual() - && (p.GetBaseDefinition()?.DeclaringType ?? p.DeclaringType).IsAssignableFrom(subTypePropertyDeclaringType)); + && (p.GetBaseDefinition()?.DeclaringType ?? p.DeclaringType!).IsAssignableFrom(subTypePropertyDeclaringType)); // don't add a virtual property that has an override if (index == -1) diff --git a/Src/Newtonsoft.Json/Utilities/StringBuffer.cs b/Src/Newtonsoft.Json/Utilities/StringBuffer.cs index 13f4f866..bc62f825 100644 --- a/Src/Newtonsoft.Json/Utilities/StringBuffer.cs +++ b/Src/Newtonsoft.Json/Utilities/StringBuffer.cs @@ -107,7 +107,7 @@ namespace Newtonsoft.Json.Utilities public string ToString(int start, int length) { - // TODO: validation + MiscellaneousUtils.Assert(_buffer != null); return new string(_buffer, start, length); } diff --git a/Src/Newtonsoft.Json/Utilities/StringUtils.cs b/Src/Newtonsoft.Json/Utilities/StringUtils.cs index e176c88f..ad763789 100644 --- a/Src/Newtonsoft.Json/Utilities/StringUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/StringUtils.cs @@ -128,7 +128,7 @@ namespace Newtonsoft.Json.Utilities buffer[5] = MathUtils.IntToHex(c & '\x000f'); } - public static TSource ForgivingCaseSensitiveFind(this IEnumerable source, Func valueSelector, string testValue) + public static TSource? ForgivingCaseSensitiveFind(this IEnumerable source, Func valueSelector, string testValue) { if (source == null) { @@ -303,6 +303,24 @@ namespace Newtonsoft.Json.Utilities #endif } + public static int IndexOf(string s, char c) + { +#if HAVE_INDEXOF_STRING_COMPARISON + return s.IndexOf(c, StringComparison.Ordinal); +#else + return s.IndexOf(c); +#endif + } + + public static string Replace(string s, string oldValue, string newValue) + { +#if HAVE_REPLACE_STRING_COMPARISON + return s.Replace(oldValue, newValue, StringComparison.Ordinal); +#else + return s.Replace(oldValue, newValue); +#endif + } + public static bool StartsWith(this string source, char value) { return (source.Length > 0 && source[0] == value); diff --git a/Src/Newtonsoft.Json/Utilities/StructMultiKey.cs b/Src/Newtonsoft.Json/Utilities/StructMultiKey.cs index 10428aaa..a36d1d15 100644 --- a/Src/Newtonsoft.Json/Utilities/StructMultiKey.cs +++ b/Src/Newtonsoft.Json/Utilities/StructMultiKey.cs @@ -43,7 +43,7 @@ namespace Newtonsoft.Json.Utilities return (Value1?.GetHashCode() ?? 0) ^ (Value2?.GetHashCode() ?? 0); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is StructMultiKey key)) { diff --git a/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs b/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs index 2e135f0a..0413f22b 100644 --- a/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs +++ b/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs @@ -36,7 +36,7 @@ using Newtonsoft.Json.Serialization; namespace Newtonsoft.Json.Utilities { - internal class ThreadSafeStore + internal class ThreadSafeStore where TKey : notnull { #if HAVE_CONCURRENT_DICTIONARY private readonly ConcurrentDictionary _concurrentStore; diff --git a/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs b/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs index 77b75691..934302d6 100644 --- a/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs +++ b/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs @@ -171,7 +171,7 @@ namespace Newtonsoft.Json.Utilities #endif } - public static Type BaseType(this Type type) + public static Type? BaseType(this Type type) { #if HAVE_FULL_REFLECTION return type.BaseType; @@ -580,7 +580,7 @@ namespace Newtonsoft.Json.Utilities public static bool AssignableToTypeName(this Type type, string fullTypeName, bool searchInterfaces, [NotNullWhen(true)]out Type? match) { - Type current = type; + Type? current = type; while (current != null) { @@ -616,7 +616,7 @@ namespace Newtonsoft.Json.Utilities public static bool ImplementInterface(this Type type, Type interfaceType) { - for (Type currentType = type; currentType != null; currentType = currentType.BaseType()) + for (Type? currentType = type; currentType != null; currentType = currentType.BaseType()) { IEnumerable interfaces = currentType.GetInterfaces(); foreach (Type i in interfaces)