Add .NET 6 target (#2677)

This commit is contained in:
James Newton-King
2022-05-16 16:12:52 +08:00
committed by GitHub
parent e42c9e4824
commit bf2e2a78e8
80 changed files with 520 additions and 408 deletions
+2 -1
View File
@@ -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},
@@ -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]
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks Condition="'$(TestFrameworks)'==''">net46;net40;net35;net20;net6.0;netcoreapp3.1;netcoreapp2.1</TargetFrameworks>
<TargetFrameworks Condition="'$(TestFrameworks)'==''">net46;net40;net35;net20;net5.0;net6.0;netcoreapp3.1;netcoreapp2.1</TargetFrameworks>
<TargetFrameworks Condition="'$(TestFrameworks)'!=''">$(TestFrameworks)</TargetFrameworks>
<LangVersion>9.0</LangVersion>
<VersionPrefix>1.0</VersionPrefix>
@@ -13,7 +13,7 @@
<RootNamespace>Newtonsoft.Json.Tests</RootNamespace>
<IsPackable>false</IsPackable>
<!-- Workaround for https://github.com/nunit/nunit3-vs-adapter/issues/296 -->
<DebugType Condition="'$(TargetFramework)' != '' AND '$(TargetFramework)' != 'netcoreapp2.1' AND '$(TargetFramework)' != 'netcoreapp3.1' AND '$(TargetFramework)' != 'net6.0'">Full</DebugType>
<DebugType Condition="'$(TargetFramework)' != '' AND '$(TargetFramework)' != 'netcoreapp2.1' AND '$(TargetFramework)' != 'netcoreapp3.1' AND '$(TargetFramework)' != 'net5.0' AND '$(TargetFramework)' != 'net6.0'">Full</DebugType>
<!-- Disabled because SourceLink isn't referenced to calculate paths -->
<DeterministicSourcePaths>false</DeterministicSourcePaths>
<!-- It's ok if a test target has exited support. Disable NETSSDK1138 warning -->
@@ -109,6 +109,27 @@
<DefineConstants>NET20;$(AdditionalConstants)</DefineConstants>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)'=='net5.0'">
<PackageReference Include="BenchmarkDotNet" Version="$(BenchmarkDotNetPackageVersion)" />
<PackageReference Include="FSharp.Core" Version="$(FSharpCorePackageVersion)" />
<PackageReference Include="System.ObjectModel" Version="$(SystemObjectModelPackageVersion)" />
<PackageReference Include="System.Runtime.Serialization.Primitives" Version="$(SystemRuntimeSerializationPrimitivesPackageVersion)" />
<PackageReference Include="System.Runtime.Serialization.Xml" Version="$(SystemRuntimeSerializationXmlPackageVersion)" />
<PackageReference Include="System.Runtime.Serialization.Formatters" Version="$(SystemRuntimeSerializationFormattersPackageVersion)" />
<PackageReference Include="System.Xml.XmlSerializer" Version="$(SystemXmlXmlDocumentPackageVersion)" />
<PackageReference Include="System.ValueTuple" Version="$(SystemValueTuplePackageVersion)" />
<PackageReference Include="Autofac" Version="$(AutofacPackageVersion)" />
<PackageReference Include="Moq" Version="$(MoqPackageVersion)" />
<PackageReference Include="xunit" Version="$(XunitPackageVersion)" />
<PackageReference Include="xunit.runner.visualstudio" Version="$(XunitRunnerVisualStudioPackageVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftNETTestSdkPackageVersion)" />
</ItemGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net5.0'">
<AssemblyTitle>Json.NET Tests .NET Standard 2.0</AssemblyTitle>
<ReferringTargetFrameworkForProjectReferences>.NETStandard,Version=v2.0</ReferringTargetFrameworkForProjectReferences>
<DefineConstants>NETSTANDARD2_0;DNXCORE50;PORTABLE;HAVE_BENCHMARKS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants)</DefineConstants>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)'=='net6.0'">
<PackageReference Include="BenchmarkDotNet" Version="$(BenchmarkDotNetPackageVersion)" />
<PackageReference Include="FSharp.Core" Version="$(FSharpCorePackageVersion)" />
@@ -125,8 +146,8 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftNETTestSdkPackageVersion)" />
</ItemGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net6.0'">
<AssemblyTitle>Json.NET Tests .NET Standard 2.0</AssemblyTitle>
<ReferringTargetFrameworkForProjectReferences>.NETStandard,Version=v2.0</ReferringTargetFrameworkForProjectReferences>
<AssemblyTitle>Json.NET Tests .NET 6.0</AssemblyTitle>
<ReferringTargetFrameworkForProjectReferences>net6.0</ReferringTargetFrameworkForProjectReferences>
<DefineConstants>NETSTANDARD2_0;DNXCORE50;PORTABLE;HAVE_BENCHMARKS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants)</DefineConstants>
</PropertyGroup>
@@ -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
@@ -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)!;
@@ -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;
@@ -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();
@@ -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();
@@ -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())
{
@@ -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))
{
@@ -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))
{
@@ -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())
@@ -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())
{
@@ -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();
@@ -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))
@@ -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<IXmlNode>(_node.Attributes.Count);
_attributes = new List<IXmlNode>(_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)
{
+2 -2
View File
@@ -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;
}
+2 -2
View File
@@ -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)
+3 -3
View File
@@ -79,7 +79,7 @@ namespace Newtonsoft.Json
return ParseObjectAsync(cancellationToken);
case State.PostValue:
Task<bool> task = ParsePostValueAsync(false, cancellationToken);
if (task.IsCompletedSucessfully())
if (task.IsCompletedSuccessfully())
{
if (task.Result)
{
@@ -542,7 +542,7 @@ namespace Newtonsoft.Json
_charPos++;
Task<bool> 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)
+1
View File
@@ -2353,6 +2353,7 @@ namespace Newtonsoft.Json
{
if (setToken)
{
MiscellaneousUtils.Assert(_chars != null);
SetToken(JsonToken.Comment, new string(_chars, initialPosition, endPosition - initialPosition));
}
}
+10 -10
View File
@@ -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);
}
+7
View File
@@ -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);
}
}
+5 -5
View File
@@ -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:
+2 -2
View File
@@ -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());
+2 -2
View File
@@ -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);
}
}
+7 -1
View File
@@ -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();
}
/// <summary>
+1 -1
View File
@@ -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;
+13 -12
View File
@@ -84,7 +84,7 @@ namespace Newtonsoft.Json.Linq
/// <summary>
/// Occurs when the items list of the collection has changed, or the collection is reset.
/// </summary>
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<PropertyDescriptor>());
}
#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));
+1 -1
View File
@@ -111,7 +111,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>
/// <c>true</c> if the specified <see cref="Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
public override bool Equals(object? obj)
{
if (obj is JEnumerable<T> enumerable)
{
+2 -2
View File
@@ -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);
}
+3 -3
View File
@@ -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)
{
+1 -1
View File
@@ -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);
}
+7 -1
View File
@@ -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);
}
/// <summary>
@@ -67,7 +67,7 @@ namespace Newtonsoft.Json.Linq
/// The value of a property for a given component.
/// </returns>
/// <param name="component">The component with the property for which to retrieve the value.</param>
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
/// </summary>
/// <param name="component">The component with the property value that is to be set.</param>
/// <param name="value">The new value.</param>
public override void SetValue(object component, object value)
public override void SetValue(object? component, object? value)
{
if (component is JObject o)
{
@@ -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<string, JToken> keyAndProperty in d1)
{
if (!d2.TryGetValue(keyAndProperty.Key, out JToken secondValue))
if (!d2.TryGetValue(keyAndProperty.Key, out JToken? secondValue))
{
return false;
}
+9 -9
View File
@@ -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)!);
}
/// <summary>
@@ -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)!);
}
/// <summary>
@@ -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)!);
}
/// <summary>
@@ -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)!);
}
/// <summary>
@@ -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!);
}
}
@@ -40,7 +40,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>
/// <c>true</c> if the specified objects are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(JToken x, JToken y)
public bool Equals(JToken? x, JToken? y)
{
return JToken.DeepEquals(x, y);
}
+25 -25
View File
@@ -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
/// <returns>
/// <c>true</c> if the specified <see cref="Object"/> is equal to the current <see cref="Object"/>; otherwise, <c>false</c>.
/// </returns>
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()!;
}
/// <summary>
@@ -924,7 +924,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public string ToString(IFormatProvider formatProvider)
public string ToString(IFormatProvider? formatProvider)
{
return ToString(null, formatProvider);
}
@@ -937,7 +937,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
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
/// <exception cref="ArgumentException">
/// <paramref name="obj"/> is not of the same type as this instance.
/// </exception>
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
}
@@ -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;
+6 -2
View File
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks Condition="'$(LibraryFrameworks)'==''">net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0</TargetFrameworks>
<TargetFrameworks Condition="'$(LibraryFrameworks)'==''">net6.0;net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0</TargetFrameworks>
<TargetFrameworks Condition="'$(LibraryFrameworks)'!=''">$(LibraryFrameworks)</TargetFrameworks>
<LangVersion>9.0</LangVersion>
<!-- version numbers will be updated by build -->
@@ -51,8 +51,12 @@
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="$(MicrosoftCodeAnalysisNetAnalyzersPackageVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="$(MicrosoftSourceLinkGitHubPackageVersion)" PrivateAssets="All" />
</ItemGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net6.0'">
<AssemblyTitle>Json.NET .NET 6.0</AssemblyTitle>
<DefineConstants>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)</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net45'">
<AssemblyTitle>Json.NET</AssemblyTitle>
<AssemblyTitle>Json.NET .NET 4.5</AssemblyTitle>
<DefineConstants>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)</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net40'">
@@ -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;
@@ -66,7 +66,7 @@ namespace Newtonsoft.Json.Serialization
// for backwards compadibility the CamelCasePropertyNamesContractResolver shares contracts between instances
StructMultiKey<Type, Type> key = new StructMultiKey<Type, Type>(GetType(), type);
Dictionary<StructMultiKey<Type, Type>, JsonContract>? cache = _contractCache;
if (cache == null || !cache.TryGetValue(key, out JsonContract contract))
if (cache == null || !cache.TryGetValue(key, out JsonContract? contract))
{
contract = CreateContract(type);
@@ -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<MemberInfo> 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<string, JToken>.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name));
throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary<string, JToken>.".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<Type> ret = new List<Type>();
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<object> 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<object>? 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);
@@ -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<string, object> mappings = GetMappings(context);
if (!mappings.TryGetBySecond(value, out string reference))
if (!mappings.TryGetBySecond(value, out string? reference))
{
_referenceCount++;
reference = _referenceCount.ToString(CultureInfo.InvariantCulture);
@@ -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<Type> genericTypeArguments = new List<Type>();
@@ -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);
}
@@ -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;
@@ -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);
}
@@ -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)
@@ -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;
}
@@ -35,7 +35,7 @@ namespace Newtonsoft.Json.Serialization
{
private class ReferenceEqualsEqualityComparer : IEqualityComparer<object>
{
bool IEqualityComparer<object>.Equals(object x, object y)
bool IEqualityComparer<object>.Equals(object? x, object? y)
{
return ReferenceEquals(x, y);
}
@@ -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))
{
@@ -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()!;
}
}
@@ -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<DataMemberAttribute>.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();
@@ -123,7 +123,7 @@ namespace Newtonsoft.Json.Serialization
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj) => Equals(obj as NamingStrategy);
public override bool Equals(object? obj) => Equals(obj as NamingStrategy);
/// <summary>
/// Compare to another NamingStrategy
@@ -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)
+3 -3
View File
@@ -95,11 +95,11 @@ namespace Newtonsoft.Json.Utilities
return cancellationToken.IsCancellationRequested ? FromCanceled<int>(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
@@ -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);
}
@@ -25,11 +25,14 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace Newtonsoft.Json.Utilities
{
internal class BidirectionalDictionary<TFirst, TSecond>
where TFirst : notnull
where TSecond : notnull
{
private readonly IDictionary<TFirst, TSecond> _firstToSecond;
private readonly IDictionary<TSecond, TFirst> _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);
}
@@ -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<T>()
{
#if !HAS_ARRAY_EMPTY
// Enumerable.Empty<T> no longer returns an empty array in .NET Core 3.0
return EmptyArrayContainer<T>.Empty;
#else
return Array.Empty<T>();
#endif
}
#if !HAS_ARRAY_EMPTY
private static class EmptyArrayContainer<T>
{
#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
}
}
@@ -168,7 +168,7 @@ namespace Newtonsoft.Json.Utilities
public virtual IEnumerator<T> GetEnumerator()
{
return (_genericCollection ?? _list.Cast<T>()).GetEnumerator();
return (_genericCollection ?? _list!.Cast<T>()).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)))))
{
@@ -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))
@@ -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, TValue>((TKey)entry.Key, (TValue)entry.Value);
array[arrayIndex++] = new KeyValuePair<TKey, TValue>((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<DictionaryEntry>().Select(de => new KeyValuePair<TKey, TValue>((TKey)de.Key, (TValue)de.Value)).GetEnumerator();
return _dictionary.Cast<DictionaryEntry>().Select(de => new KeyValuePair<TKey, TValue>((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()
{
@@ -37,7 +37,7 @@ namespace Newtonsoft.Json.Utilities
private readonly DynamicProxy<T> _proxy;
internal DynamicProxyMetaObject(Expression expression, T value, DynamicProxy<T> 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<T>).GetMethod(methodName),
typeof(DynamicProxy<T>).GetMethod(methodName)!,
callArgs
),
resultMetaObject.Expression,
@@ -304,7 +304,7 @@ namespace Newtonsoft.Json.Utilities
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
typeof(DynamicProxy<T>).GetMethod(methodName)!,
callArgs
),
result,
@@ -342,7 +342,7 @@ namespace Newtonsoft.Json.Utilities
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
typeof(DynamicProxy<T>).GetMethod(methodName)!,
callArgs
),
Expression.Empty(),
@@ -366,7 +366,7 @@ namespace Newtonsoft.Json.Utilities
public override IEnumerable<string> 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();
}
@@ -51,7 +51,7 @@ namespace Newtonsoft.Json.Utilities
public override ObjectConstructor<object> 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<T, object?> CreateMethodCall<T>(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<T, object?> CreateGet<T>(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<T, object?> 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<T, object?> CreateSet<T>(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<T, object?> CreateSet<T>(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);
+12 -12
View File
@@ -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<object?>(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<object?>(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<DynamicMetaObject>());
@@ -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 });
+2 -2
View File
@@ -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<EnumMemberAttribute>()
.Select(a => a.Value)
.SingleOrDefault();
@@ -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<T>(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<T>(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)
+13 -13
View File
@@ -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<object?>(isUnionMethodInfo)!;
@@ -68,23 +68,23 @@ namespace Newtonsoft.Json.Utilities
MethodInfo getUnionCasesMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "GetUnionCases", BindingFlags.Public | BindingFlags.Static);
GetUnionCases = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object?>(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<object>(unionCaseInfo.GetProperty("Name")!)!;
GetUnionCaseInfoTag = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(unionCaseInfo.GetProperty("Tag")!)!;
GetUnionCaseInfoDeclaringType = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(unionCaseInfo.GetProperty("DeclaringType")!)!;
GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(unionCaseInfo.GetMethod("GetFields"));
GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(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<object?, object> 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<object?, object?> call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object?>(innerMethodInfo);
MethodCall<object?, object> invoke = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object?>(invokeFunc)!;
@@ -175,17 +175,17 @@ namespace Newtonsoft.Json.Utilities
public ObjectConstructor<object> 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<object>)creatorGeneric.Invoke(this, null);
return (ObjectConstructor<object>)creatorGeneric.Invoke(this, null)!;
}
public ObjectConstructor<object> BuildMapCreator<TKey, TValue>()
{
Type genericMapType = _mapType.MakeGenericType(typeof(TKey), typeof(TValue));
ConstructorInfo ctor = genericMapType.GetConstructor(new[] { typeof(IEnumerable<Tuple<TKey, TValue>>) });
ConstructorInfo ctor = genericMapType.GetConstructor(new[] { typeof(IEnumerable<Tuple<TKey, TValue>>) })!;
ObjectConstructor<object> ctorDelegate = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(ctor);
ObjectConstructor<object> creator = args =>
@@ -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();
@@ -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);
}
@@ -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<T, object?> CreateMethodCall<T>(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);
}
@@ -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)
{
@@ -23,6 +23,8 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !HAVE_NULLABLE_ATTRIBUTES
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>Specifies that an output will not be null even if the corresponding type allows it.</summary>
@@ -71,4 +73,6 @@ namespace System.Diagnostics.CodeAnalysis
/// <summary>Gets the condition parameter value.</summary>
public bool ParameterValue { get; }
}
}
}
#endif
@@ -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
/// <param name="member">The member.</param>
/// <param name="target">The target object.</param>
/// <returns>The member's value on the object.</returns>
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<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr)
private static void GetChildPrivateFields(IList<MemberInfo> 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<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr)
private static void GetChildPrivateProperties(IList<PropertyInfo> 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)
@@ -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);
}
+19 -1
View File
@@ -128,7 +128,7 @@ namespace Newtonsoft.Json.Utilities
buffer[5] = MathUtils.IntToHex(c & '\x000f');
}
public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue)
public static TSource? ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> 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);
@@ -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<T1, T2> key))
{
@@ -36,7 +36,7 @@ using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
internal class ThreadSafeStore<TKey, TValue>
internal class ThreadSafeStore<TKey, TValue> where TKey : notnull
{
#if HAVE_CONCURRENT_DICTIONARY
private readonly ConcurrentDictionary<TKey, TValue> _concurrentStore;
@@ -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<Type> interfaces = currentType.GetInterfaces();
foreach (Type i in interfaces)