Update Newtonsoft.Json project to use nullable reference types (#1950)

This commit is contained in:
James Newton-King
2019-07-29 09:13:42 +12:00
committed by GitHub
parent f940f21804
commit cdf10151d5
169 changed files with 2264 additions and 1859 deletions
+1 -1
View File
@@ -14,7 +14,7 @@
$workingName = if ($workingName) {$workingName} else {"Working"}
$assemblyVersion = if ($assemblyVersion) {$assemblyVersion} else {$majorVersion + '.0.0'}
$netCliChannel = "2.0"
$netCliVersion = "2.2.105"
$netCliVersion = "3.0.100-preview8-013317"
$nugetUrl = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
$baseDir = resolve-path ..
@@ -160,6 +160,14 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual("<Time>0001-01-01T00:00:00</Time>", xmlNode.OuterXml);
}
[Test]
public void XmlNode_Null()
{
string json = JsonConvert.SerializeXmlNode(null);
Assert.AreEqual("null", json);
}
[Test]
public void XmlNode_Roundtrip_PropertyNameWithColon()
{
@@ -305,6 +313,14 @@ namespace Newtonsoft.Json.Tests.Converters
}
#if !NET20
[Test]
public void XNode_Null()
{
string json = JsonConvert.SerializeXNode(null);
Assert.AreEqual("null", json);
}
[Test]
public void XNode_UnescapeTextContent()
{
+8 -7
View File
@@ -1563,14 +1563,15 @@ namespace Newtonsoft.Json.Tests
public int Overload { get; set; }
}
[Test]
public void JsonConverterConstructor_OverloadsWithBaseTypes()
{
OverloadWithBaseType value = new OverloadWithBaseType();
string json = JsonConvert.SerializeObject(value);
//[Test]
//[Ignore("https://github.com/dotnet/roslyn/issues/36974")]
//public void JsonConverterConstructor_OverloadsWithBaseTypes()
//{
// OverloadWithBaseType value = new OverloadWithBaseType();
// string json = JsonConvert.SerializeObject(value);
Assert.AreEqual("{\"Overload\":\"IList<string>\"}", json);
}
// Assert.AreEqual("{\"Overload\":\"IList<string>\"}", json);
//}
[Test]
@@ -242,6 +242,26 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(2, a[2].BeforeSelf().Count());
}
[Test]
public void BeforeSelf_NoParent_ReturnEmpty()
{
JObject o = new JObject();
List<JToken> result = o.BeforeSelf().ToList();
Assert.AreEqual(0, result.Count);
}
[Test]
public void BeforeSelf_OnlyChild_ReturnEmpty()
{
JArray a = new JArray();
JObject o = new JObject();
a.Add(o);
List<JToken> result = o.BeforeSelf().ToList();
Assert.AreEqual(0, result.Count);
}
[Test]
public void Casting()
{
@@ -45,33 +45,12 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void AndExpressionTest()
{
CompositeExpression compositeExpression = new CompositeExpression
CompositeExpression compositeExpression = new CompositeExpression(QueryOperator.And)
{
Operator = QueryOperator.And,
Expressions = new List<QueryExpression>
{
new BooleanQueryExpression
{
Operator = QueryOperator.Exists,
Left = new List<PathFilter>
{
new FieldFilter
{
Name = "FirstName"
}
}
},
new BooleanQueryExpression
{
Operator = QueryOperator.Exists,
Left = new List<PathFilter>
{
new FieldFilter
{
Name = "LastName"
}
}
}
new BooleanQueryExpression(QueryOperator.Exists, new List<PathFilter> { new FieldFilter("FirstName") }, null),
new BooleanQueryExpression(QueryOperator.Exists, new List<PathFilter> { new FieldFilter("LastName") }, null)
}
};
@@ -103,33 +82,12 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void OrExpressionTest()
{
CompositeExpression compositeExpression = new CompositeExpression
CompositeExpression compositeExpression = new CompositeExpression(QueryOperator.Or)
{
Operator = QueryOperator.Or,
Expressions = new List<QueryExpression>
{
new BooleanQueryExpression
{
Operator = QueryOperator.Exists,
Left = new List<PathFilter>
{
new FieldFilter
{
Name = "FirstName"
}
}
},
new BooleanQueryExpression
{
Operator = QueryOperator.Exists,
Left = new List<PathFilter>
{
new FieldFilter
{
Name = "LastName"
}
}
}
new BooleanQueryExpression(QueryOperator.Exists, new List<PathFilter> { new FieldFilter("FirstName") }, null),
new BooleanQueryExpression(QueryOperator.Exists, new List<PathFilter> { new FieldFilter("LastName") }, null)
}
};
@@ -161,30 +119,14 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void BooleanExpressionTest_RegexEqualsOperator()
{
BooleanQueryExpression e1 = new BooleanQueryExpression
{
Operator = QueryOperator.RegexEquals,
Right = new JValue("/foo.*d/"),
Left = new List<PathFilter>
{
new ArrayIndexFilter()
}
};
BooleanQueryExpression e1 = new BooleanQueryExpression(QueryOperator.RegexEquals, new List<PathFilter> { new ArrayIndexFilter() }, new JValue("/foo.*d/"));
Assert.IsTrue(e1.IsMatch(null, new JArray("food")));
Assert.IsTrue(e1.IsMatch(null, new JArray("fooood and drink")));
Assert.IsFalse(e1.IsMatch(null, new JArray("FOOD")));
Assert.IsFalse(e1.IsMatch(null, new JArray("foo", "foog", "good")));
BooleanQueryExpression e2 = new BooleanQueryExpression
{
Operator = QueryOperator.RegexEquals,
Right = new JValue("/Foo.*d/i"),
Left = new List<PathFilter>
{
new ArrayIndexFilter()
}
};
BooleanQueryExpression e2 = new BooleanQueryExpression(QueryOperator.RegexEquals, new List<PathFilter> { new ArrayIndexFilter() }, new JValue("/Foo.*d/i"));
Assert.IsTrue(e2.IsMatch(null, new JArray("food")));
Assert.IsTrue(e2.IsMatch(null, new JArray("fooood and drink")));
@@ -195,28 +137,12 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void BooleanExpressionTest_RegexEqualsOperator_CornerCase()
{
BooleanQueryExpression e1 = new BooleanQueryExpression
{
Operator = QueryOperator.RegexEquals,
Right = new JValue("/// comment/"),
Left = new List<PathFilter>
{
new ArrayIndexFilter()
}
};
BooleanQueryExpression e1 = new BooleanQueryExpression(QueryOperator.RegexEquals, new List<PathFilter> { new ArrayIndexFilter() }, new JValue("/// comment/"));
Assert.IsTrue(e1.IsMatch(null, new JArray("// comment")));
Assert.IsFalse(e1.IsMatch(null, new JArray("//comment", "/ comment")));
BooleanQueryExpression e2 = new BooleanQueryExpression
{
Operator = QueryOperator.RegexEquals,
Right = new JValue("/<tag>.*</tag>/i"),
Left = new List<PathFilter>
{
new ArrayIndexFilter()
}
};
BooleanQueryExpression e2 = new BooleanQueryExpression(QueryOperator.RegexEquals, new List<PathFilter> { new ArrayIndexFilter() }, new JValue("/<tag>.*</tag>/i"));
Assert.IsTrue(e2.IsMatch(null, new JArray("<Tag>Test</Tag>", "")));
Assert.IsFalse(e2.IsMatch(null, new JArray("<tag>Test<tag>")));
@@ -225,15 +151,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void BooleanExpressionTest()
{
BooleanQueryExpression e1 = new BooleanQueryExpression
{
Operator = QueryOperator.LessThan,
Right = new JValue(3),
Left = new List<PathFilter>
{
new ArrayIndexFilter()
}
};
BooleanQueryExpression e1 = new BooleanQueryExpression(QueryOperator.LessThan, new List<PathFilter> { new ArrayIndexFilter() }, new JValue(3));
Assert.IsTrue(e1.IsMatch(null, new JArray(1, 2, 3, 4, 5)));
Assert.IsTrue(e1.IsMatch(null, new JArray(2, 3, 4, 5)));
@@ -241,15 +159,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
Assert.IsFalse(e1.IsMatch(null, new JArray(4, 5)));
Assert.IsFalse(e1.IsMatch(null, new JArray("11", 5)));
BooleanQueryExpression e2 = new BooleanQueryExpression
{
Operator = QueryOperator.LessThanOrEquals,
Right = new JValue(3),
Left = new List<PathFilter>
{
new ArrayIndexFilter()
}
};
BooleanQueryExpression e2 = new BooleanQueryExpression(QueryOperator.LessThanOrEquals, new List<PathFilter> { new ArrayIndexFilter() }, new JValue(3));
Assert.IsTrue(e2.IsMatch(null, new JArray(1, 2, 3, 4, 5)));
Assert.IsTrue(e2.IsMatch(null, new JArray(2, 3, 4, 5)));
@@ -261,15 +171,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void BooleanExpressionTest_GreaterThanOperator()
{
BooleanQueryExpression e1 = new BooleanQueryExpression
{
Operator = QueryOperator.GreaterThan,
Right = new JValue(3),
Left = new List<PathFilter>
{
new ArrayIndexFilter()
}
};
BooleanQueryExpression e1 = new BooleanQueryExpression(QueryOperator.GreaterThan, new List<PathFilter> { new ArrayIndexFilter() }, new JValue(3));
Assert.IsTrue(e1.IsMatch(null, new JArray("2", "26")));
Assert.IsTrue(e1.IsMatch(null, new JArray(2, 26)));
@@ -280,15 +182,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
[Test]
public void BooleanExpressionTest_GreaterThanOrEqualsOperator()
{
BooleanQueryExpression e1 = new BooleanQueryExpression
{
Operator = QueryOperator.GreaterThanOrEquals,
Right = new JValue(3),
Left = new List<PathFilter>
{
new ArrayIndexFilter()
}
};
BooleanQueryExpression e1 = new BooleanQueryExpression(QueryOperator.GreaterThanOrEquals, new List<PathFilter> { new ArrayIndexFilter() }, new JValue(3));
Assert.IsTrue(e1.IsMatch(null, new JArray("2", "26")));
Assert.IsTrue(e1.IsMatch(null, new JArray(2, 26)));
@@ -42,8 +42,8 @@
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)'=='net46'">
<PackageReference Include="NUnit" Version="3.10.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
<PackageReference Include="Autofac" Version="4.6.2" />
<PackageReference Include="BenchmarkDotNet" Version="0.10.10" />
<PackageReference Include="FSharp.Core" Version="4.2.3" />
@@ -66,8 +66,8 @@
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)'=='net451'">
<PackageReference Include="NUnit" Version="3.10.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
<PackageReference Include="Autofac" Version="4.6.2" />
<PackageReference Include="FSharp.Core" Version="4.2.3" />
<PackageReference Include="System.Buffers" Version="4.4.0" />
@@ -89,8 +89,8 @@
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)'=='net452'">
<PackageReference Include="NUnit" Version="3.10.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
<PackageReference Include="Autofac" Version="4.6.2" />
<PackageReference Include="FSharp.Core" Version="4.2.3" />
<PackageReference Include="System.Buffers" Version="4.4.0" />
@@ -112,8 +112,8 @@
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)'=='net40'">
<PackageReference Include="NUnit" Version="3.10.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
<PackageReference Include="System.ValueTuple" Version="4.4.0" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Web" />
@@ -129,8 +129,8 @@
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)'=='net35'">
<PackageReference Include="NUnit" Version="3.10.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
<Reference Include="System.Web" />
<Reference Include="System.Data.Linq" />
<Reference Include="System.Data.Entity" />
@@ -144,8 +144,8 @@
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)'=='net20'">
<PackageReference Include="NUnit" Version="3.10.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
<Reference Include="System.Web" />
</ItemGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net20'">
@@ -24,6 +24,7 @@
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
@@ -727,6 +728,17 @@ namespace Newtonsoft.Json.Tests.Serialization
}
}
[Test]
public void NonGenericDictionary_KeyValueTypes()
{
DefaultContractResolver resolver = new DefaultContractResolver();
JsonDictionaryContract c = (JsonDictionaryContract)resolver.ResolveContract(typeof(IDictionary));
Assert.IsNull(c.DictionaryKeyType);
Assert.IsNull(c.DictionaryValueType);
}
[Test]
public void DefaultContractResolverIgnoreIsSpecifiedTrue()
{
+3 -5
View File
@@ -212,11 +212,9 @@ namespace Newtonsoft.Json.Tests
public static string ResolvePath(string path)
{
#if !DNXCORE50
return Path.Combine(TestContext.CurrentContext.TestDirectory, path);
#else
return path;
#endif
var assemblyPath = Path.GetDirectoryName(typeof(TestFixtureBase).Assembly().Location);
return Path.Combine(assemblyPath, path);
}
protected string GetOffset(DateTime d, DateFormatHandling dateFormatHandling)
@@ -25,6 +25,8 @@
using System;
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal enum BsonBinaryType : byte
@@ -29,6 +29,8 @@ using System.IO;
using System.Text;
using Newtonsoft.Json.Utilities;
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal class BsonBinaryWriter
+2
View File
@@ -26,6 +26,8 @@
using System;
using Newtonsoft.Json.Utilities;
#nullable disable
namespace Newtonsoft.Json.Bson
{
/// <summary>
+2
View File
@@ -32,6 +32,8 @@ using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
#nullable disable
namespace Newtonsoft.Json.Bson
{
/// <summary>
+2
View File
@@ -26,6 +26,8 @@
using System.Collections;
using System.Collections.Generic;
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal abstract class BsonToken
+2
View File
@@ -23,6 +23,8 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal enum BsonType : sbyte
+2
View File
@@ -35,6 +35,8 @@ using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using System.Globalization;
#nullable disable
namespace Newtonsoft.Json.Bson
{
/// <summary>
@@ -51,7 +51,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
@@ -70,7 +70,7 @@ namespace Newtonsoft.Json.Converters
if (value.GetType().FullName == BinaryTypeName)
{
EnsureReflectionObject(value.GetType());
return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName);
return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName)!;
}
#endif
#if HAVE_ADO_NET
@@ -101,7 +101,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
@@ -123,7 +123,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
@@ -140,7 +140,7 @@ namespace Newtonsoft.Json.Converters
{
EnsureReflectionObject(t);
return _reflectionObject.Creator(data);
return _reflectionObject.Creator!(data);
}
#endif
@@ -28,6 +28,8 @@ using Newtonsoft.Json.Bson;
using System.Globalization;
using Newtonsoft.Json.Utilities;
#nullable disable
namespace Newtonsoft.Json.Converters
{
/// <summary>
@@ -41,7 +41,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new NotSupportedException("CustomCreationConverter should only be used while deserializing.");
}
@@ -54,7 +54,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
@@ -41,7 +41,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
@@ -50,7 +50,7 @@ namespace Newtonsoft.Json.Converters
}
DataSet dataSet = (DataSet)value;
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
DataTableConverter converter = new DataTableConverter();
@@ -74,7 +74,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
@@ -92,10 +92,10 @@ 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);
dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer)!;
if (!exists)
{
@@ -45,7 +45,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
@@ -54,7 +54,7 @@ namespace Newtonsoft.Json.Converters
}
DataTable table = (DataTable)value;
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartArray();
@@ -87,7 +87,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
@@ -106,7 +106,7 @@ namespace Newtonsoft.Json.Converters
// populate the name from the property name
if (reader.TokenType == JsonToken.PropertyName)
{
dt.TableName = (string)reader.Value;
dt.TableName = (string)reader.Value!;
reader.ReadAndAssert();
@@ -140,7 +140,7 @@ namespace Newtonsoft.Json.Converters
while (reader.TokenType == JsonToken.PropertyName)
{
string columnName = (string)reader.Value;
string columnName = (string)reader.Value!;
reader.ReadAndAssert();
@@ -177,7 +177,7 @@ namespace Newtonsoft.Json.Converters
reader.ReadAndAssert();
}
List<object> o = new List<object>();
List<object?> o = new List<object?>();
while (reader.TokenType != JsonToken.EndArray)
{
@@ -218,7 +218,7 @@ namespace Newtonsoft.Json.Converters
case JsonToken.String:
case JsonToken.Date:
case JsonToken.Bytes:
return reader.ValueType;
return reader.ValueType!;
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.EndArray:
@@ -48,17 +48,32 @@ namespace Newtonsoft.Json.Converters
#region UnionDefinition
internal class Union
{
public List<UnionCase> Cases;
public FSharpFunction TagReader { get; set; }
public readonly FSharpFunction TagReader;
public readonly List<UnionCase> Cases;
public Union(FSharpFunction tagReader, List<UnionCase> cases)
{
TagReader = tagReader;
Cases = cases;
}
}
internal class UnionCase
{
public int Tag;
public string Name;
public PropertyInfo[] Fields;
public FSharpFunction FieldReader;
public FSharpFunction Constructor;
public readonly int Tag;
public readonly string Name;
public readonly PropertyInfo[] Fields;
public readonly FSharpFunction FieldReader;
public readonly FSharpFunction Constructor;
public UnionCase(int tag, string name, PropertyInfo[] fields, FSharpFunction fieldReader, FSharpFunction constructor)
{
Tag = tag;
Name = name;
Fields = fields;
FieldReader = fieldReader;
Constructor = constructor;
}
}
#endregion
@@ -74,31 +89,28 @@ namespace Newtonsoft.Json.Converters
// need to get declaring type to avoid duplicate Unions in cache
// hacky but I can't find an API to get the declaring type without GetUnionCases
object[] cases = (object[])FSharpUtils.GetUnionCases(null, t, null);
object[] cases = (object[])FSharpUtils.GetUnionCases(null, t, null)!;
object caseInfo = cases.First();
Type unionType = (Type)FSharpUtils.GetUnionCaseInfoDeclaringType(caseInfo);
Type unionType = (Type)FSharpUtils.GetUnionCaseInfoDeclaringType(caseInfo)!;
return unionType;
}
private static Union CreateUnion(Type t)
{
Union u = new Union();
Union u = new Union((FSharpFunction)FSharpUtils.PreComputeUnionTagReader(null, t, null), new List<UnionCase>());
u.TagReader = (FSharpFunction)FSharpUtils.PreComputeUnionTagReader(null, t, null);
u.Cases = new List<UnionCase>();
object[] cases = (object[])FSharpUtils.GetUnionCases(null, t, null);
object[] cases = (object[])FSharpUtils.GetUnionCases(null, t, null)!;
foreach (object unionCaseInfo in cases)
{
UnionCase unionCase = new UnionCase();
unionCase.Tag = (int)FSharpUtils.GetUnionCaseInfoTag(unionCaseInfo);
unionCase.Name = (string)FSharpUtils.GetUnionCaseInfoName(unionCaseInfo);
unionCase.Fields = (PropertyInfo[])FSharpUtils.GetUnionCaseInfoFields(unionCaseInfo);
unionCase.FieldReader = (FSharpFunction)FSharpUtils.PreComputeUnionReader(null, unionCaseInfo, null);
unionCase.Constructor = (FSharpFunction)FSharpUtils.PreComputeUnionConstructor(null, unionCaseInfo, null);
UnionCase unionCase = new UnionCase(
(int)FSharpUtils.GetUnionCaseInfoTag(unionCaseInfo),
(string)FSharpUtils.GetUnionCaseInfoName(unionCaseInfo),
(PropertyInfo[])FSharpUtils.GetUnionCaseInfoFields(unionCaseInfo)!,
(FSharpFunction)FSharpUtils.PreComputeUnionReader(null, unionCaseInfo, null),
(FSharpFunction)FSharpUtils.PreComputeUnionConstructor(null, unionCaseInfo, null));
u.Cases.Add(unionCase);
}
@@ -112,9 +124,15 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
if (value == null)
{
writer.WriteNull();
return;
}
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
Type unionType = UnionTypeLookupCache.Get(value.GetType());
Union union = UnionCache.Get(unionType);
@@ -127,7 +145,7 @@ namespace Newtonsoft.Json.Converters
writer.WriteValue(caseInfo.Name);
if (caseInfo.Fields != null && caseInfo.Fields.Length > 0)
{
object[] fields = (object[])caseInfo.FieldReader.Invoke(value);
object[] fields = (object[])caseInfo.FieldReader.Invoke(value)!;
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(FieldsPropertyName) : FieldsPropertyName);
writer.WriteStartArray();
@@ -148,30 +166,30 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
UnionCase caseInfo = null;
string caseName = null;
JArray fields = null;
UnionCase? caseInfo = null;
string? caseName = null;
JArray? fields = null;
// start object
reader.ReadAndAssert();
while (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = reader.Value.ToString();
string propertyName = reader.Value!.ToString();
if (string.Equals(propertyName, CasePropertyName, StringComparison.OrdinalIgnoreCase))
{
reader.ReadAndAssert();
Union union = UnionCache.Get(objectType);
caseName = reader.Value.ToString();
caseName = reader.Value!.ToString();
caseInfo = union.Cases.SingleOrDefault(c => c.Name == caseName);
@@ -203,7 +221,7 @@ namespace Newtonsoft.Json.Converters
throw JsonSerializationException.Create(reader, "No '{0}' property with union name found.".FormatWith(CultureInfo.InvariantCulture, CasePropertyName));
}
object[] typedFieldValues = new object[caseInfo.Fields.Length];
object?[] typedFieldValues = new object?[caseInfo.Fields.Length];
if (caseInfo.Fields.Length > 0 && fields == null)
{
@@ -50,16 +50,22 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
EnsureReflectionObject(value.GetType());
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
string keyName = (string)_reflectionObject.GetValue(value, KeyPropertyName);
object keyValue = _reflectionObject.GetValue(value, ValuePropertyName);
string keyName = (string)_reflectionObject.GetValue(value, KeyPropertyName)!;
object? keyValue = _reflectionObject.GetValue(value, ValuePropertyName);
Type keyValueType = keyValue?.GetType();
Type? keyValueType = keyValue?.GetType();
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyPropertyName) : KeyPropertyName);
@@ -71,7 +77,7 @@ namespace Newtonsoft.Json.Converters
if (keyValueType != null)
{
if (JsonSerializerInternalWriter.TryConvertToString(keyValue, keyValueType, out string valueJson))
if (JsonSerializerInternalWriter.TryConvertToString(keyValue!, keyValueType, out string? valueJson))
{
writer.WriteValue(valueJson);
}
@@ -92,7 +98,7 @@ namespace Newtonsoft.Json.Converters
{
reader.ReadAndAssert();
if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase))
if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value?.ToString(), propertyName, StringComparison.OrdinalIgnoreCase))
{
throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName));
}
@@ -106,19 +112,19 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
EnsureReflectionObject(objectType);
object entityKeyMember = _reflectionObject.Creator();
object entityKeyMember = _reflectionObject.Creator!();
ReadAndAssertProperty(reader, KeyPropertyName);
reader.ReadAndAssert();
_reflectionObject.SetValue(entityKeyMember, KeyPropertyName, reader.Value.ToString());
_reflectionObject.SetValue(entityKeyMember, KeyPropertyName, reader.Value?.ToString());
ReadAndAssertProperty(reader, TypePropertyName);
reader.ReadAndAssert();
string type = reader.Value.ToString();
string? type = reader.Value?.ToString();
Type t = Type.GetType(type);
@@ -46,7 +46,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
// can write is set to false
}
@@ -59,12 +59,12 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
return ReadValue(reader);
}
private object ReadValue(JsonReader reader)
private object? ReadValue(JsonReader reader)
{
if (!reader.MoveToContent())
{
@@ -89,7 +89,7 @@ namespace Newtonsoft.Json.Converters
private object ReadList(JsonReader reader)
{
IList<object> list = new List<object>();
IList<object?> list = new List<object?>();
while (reader.Read())
{
@@ -98,7 +98,7 @@ namespace Newtonsoft.Json.Converters
case JsonToken.Comment:
break;
default:
object v = ReadValue(reader);
object? v = ReadValue(reader);
list.Add(v);
break;
@@ -112,21 +112,21 @@ namespace Newtonsoft.Json.Converters
private object ReadObject(JsonReader reader)
{
IDictionary<string, object> expandoObject = new ExpandoObject();
IDictionary<string, object?> expandoObject = new ExpandoObject();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string propertyName = reader.Value.ToString();
string propertyName = reader.Value!.ToString();
if (!reader.Read())
{
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
}
object v = ReadValue(reader);
object? v = ReadValue(reader);
expandoObject[propertyName] = v;
break;
@@ -37,8 +37,8 @@ namespace Newtonsoft.Json.Converters
private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
private string _dateTimeFormat;
private CultureInfo _culture;
private string? _dateTimeFormat;
private CultureInfo? _culture;
/// <summary>
/// Gets or sets the date time styles used when converting a date to and from JSON.
@@ -54,7 +54,7 @@ namespace Newtonsoft.Json.Converters
/// Gets or sets the date time format used when converting a date to and from JSON.
/// </summary>
/// <value>The date time format used when converting a date to and from JSON.</value>
public string DateTimeFormat
public string? DateTimeFormat
{
get => _dateTimeFormat ?? string.Empty;
set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value;
@@ -76,7 +76,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
string text;
@@ -104,7 +104,7 @@ namespace Newtonsoft.Json.Converters
#endif
else
{
throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)));
throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)!));
}
writer.WriteValue(text);
@@ -118,7 +118,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
bool nullable = ReflectionUtils.IsNullableType(objectType);
if (reader.TokenType == JsonToken.Null)
@@ -142,7 +142,7 @@ namespace Newtonsoft.Json.Converters
#if HAVE_DATE_TIME_OFFSET
if (t == typeof(DateTimeOffset))
{
return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value);
return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value!);
}
// converter is expected to return a DateTime
@@ -160,7 +160,7 @@ namespace Newtonsoft.Json.Converters
throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
string dateText = reader.Value.ToString();
string? dateText = reader.Value?.ToString();
if (string.IsNullOrEmpty(dateText) && nullable)
{
@@ -40,7 +40,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
long ticks;
@@ -74,7 +74,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
@@ -86,12 +86,12 @@ namespace Newtonsoft.Json.Converters
return null;
}
if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal))
{
throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
}
if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime d, out string errorMessage))
if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime d, out string? errorMessage))
{
throw JsonSerializationException.Create(reader, errorMessage);
}
@@ -56,11 +56,17 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
ReflectionObject reflectionObject = ReflectionObjectPerType.Get(value.GetType());
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName);
@@ -78,7 +84,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
@@ -90,8 +96,8 @@ namespace Newtonsoft.Json.Converters
return null;
}
object key = null;
object value = null;
object? key = null;
object? value = null;
reader.ReadAndAssert();
@@ -105,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);
@@ -126,7 +132,7 @@ namespace Newtonsoft.Json.Converters
reader.ReadAndAssert();
}
return reflectionObject.Creator(key, value);
return reflectionObject.Creator!(key, value);
}
/// <summary>
@@ -47,7 +47,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
@@ -84,7 +84,7 @@ namespace Newtonsoft.Json.Converters
// 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode
// ('.' matches everything), and 'u' to make \w, \W, etc. match unicode.
string options = null;
string? options = null;
if (HasFlag(regex.Options, RegexOptions.IgnoreCase))
{
@@ -114,7 +114,7 @@ namespace Newtonsoft.Json.Converters
private void WriteJson(JsonWriter writer, Regex regex, JsonSerializer serializer)
{
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(PatternName) : PatternName);
@@ -132,7 +132,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
@@ -149,7 +149,7 @@ namespace Newtonsoft.Json.Converters
private object ReadRegexString(JsonReader reader)
{
string regexText = (string)reader.Value;
string regexText = (string)reader.Value!;
if (regexText.Length > 0 && regexText[0] == '/')
{
@@ -171,7 +171,7 @@ namespace Newtonsoft.Json.Converters
private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer)
{
string pattern = null;
string? pattern = null;
RegexOptions? options = null;
while (reader.Read())
@@ -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())
{
@@ -188,7 +188,7 @@ namespace Newtonsoft.Json.Converters
if (string.Equals(propertyName, PatternName, StringComparison.OrdinalIgnoreCase))
{
pattern = (string)reader.Value;
pattern = (string?)reader.Value;
}
else if (string.Equals(propertyName, OptionsName, StringComparison.OrdinalIgnoreCase))
{
@@ -82,7 +82,7 @@ namespace Newtonsoft.Json.Converters
/// Gets or sets the naming strategy used to resolve how enum text is written.
/// </summary>
/// <value>The naming strategy used to resolve how enum text is written.</value>
public NamingStrategy NamingStrategy { get; set; }
public NamingStrategy? NamingStrategy { get; set; }
/// <summary>
/// Gets or sets a value indicating whether integer values are allowed when serializing and deserializing.
@@ -175,7 +175,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
@@ -185,7 +185,7 @@ namespace Newtonsoft.Json.Converters
Enum e = (Enum)value;
if (!EnumUtils.TryToString(e.GetType(), value, NamingStrategy, out string enumName))
if (!EnumUtils.TryToString(e.GetType(), value, NamingStrategy, out string? enumName))
{
if (!AllowIntegerValues)
{
@@ -209,7 +209,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
@@ -228,14 +228,14 @@ namespace Newtonsoft.Json.Converters
{
if (reader.TokenType == JsonToken.String)
{
string enumText = reader.Value.ToString();
string? enumText = reader.Value?.ToString();
if (enumText == string.Empty && isNullable)
if (string.IsNullOrEmpty(enumText) && isNullable)
{
return null;
}
return EnumUtils.ParseEnum(t, NamingStrategy, enumText, !AllowIntegerValues);
return EnumUtils.ParseEnum(t, NamingStrategy, enumText!, !AllowIntegerValues);
}
if (reader.TokenType == JsonToken.Integer)
@@ -42,7 +42,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
long seconds;
@@ -77,7 +77,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
bool nullable = ReflectionUtils.IsNullable(objectType);
if (reader.TokenType == JsonToken.Null)
@@ -94,11 +94,11 @@ namespace Newtonsoft.Json.Converters
if (reader.TokenType == JsonToken.Integer)
{
seconds = (long)reader.Value;
seconds = (long)reader.Value!;
}
else if (reader.TokenType == JsonToken.String)
{
if (!long.TryParse((string)reader.Value, out seconds))
if (!long.TryParse((string)reader.Value!, out seconds))
{
throw JsonSerializationException.Create(reader, "Cannot convert invalid value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
@@ -40,7 +40,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
@@ -64,7 +64,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
@@ -76,7 +76,7 @@ namespace Newtonsoft.Json.Converters
{
try
{
Version v = new Version((string)reader.Value);
Version v = new Version((string)reader.Value!);
return v;
}
catch (Exception ex)
+136 -131
View File
@@ -38,6 +38,7 @@ using System.Xml.Linq;
#endif
using Newtonsoft.Json.Utilities;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
namespace Newtonsoft.Json.Converters
{
@@ -53,44 +54,44 @@ namespace Newtonsoft.Json.Converters
_document = document;
}
public IXmlNode CreateComment(string data)
public IXmlNode CreateComment(string? data)
{
return new XmlNodeWrapper(_document.CreateComment(data));
}
public IXmlNode CreateTextNode(string text)
public IXmlNode CreateTextNode(string? text)
{
return new XmlNodeWrapper(_document.CreateTextNode(text));
}
public IXmlNode CreateCDataSection(string data)
public IXmlNode CreateCDataSection(string? data)
{
return new XmlNodeWrapper(_document.CreateCDataSection(data));
}
public IXmlNode CreateWhitespace(string text)
public IXmlNode CreateWhitespace(string? text)
{
return new XmlNodeWrapper(_document.CreateWhitespace(text));
}
public IXmlNode CreateSignificantWhitespace(string text)
public IXmlNode CreateSignificantWhitespace(string? text)
{
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));
}
@@ -105,7 +106,7 @@ namespace Newtonsoft.Json.Converters
return new XmlElementWrapper(_document.CreateElement(qualifiedName, namespaceUri));
}
public IXmlNode CreateAttribute(string name, string value)
public IXmlNode CreateAttribute(string name, string? value)
{
XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(name));
attribute.Value = value;
@@ -113,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;
@@ -121,7 +122,7 @@ namespace Newtonsoft.Json.Converters
return attribute;
}
public IXmlElement DocumentElement
public IXmlElement? DocumentElement
{
get
{
@@ -149,7 +150,7 @@ namespace Newtonsoft.Json.Converters
{
XmlNodeWrapper xmlAttributeWrapper = (XmlNodeWrapper)attribute;
_element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode);
_element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode!);
}
public string GetPrefixOfNamespace(string namespaceUri)
@@ -204,26 +205,26 @@ namespace Newtonsoft.Json.Converters
public string InternalSubset => _documentType.InternalSubset;
public override string LocalName => "DOCTYPE";
public override string? LocalName => "DOCTYPE";
}
#endif
internal class XmlNodeWrapper : IXmlNode
{
private readonly XmlNode _node;
private List<IXmlNode> _childNodes;
private List<IXmlNode> _attributes;
private List<IXmlNode>? _childNodes;
private List<IXmlNode>? _attributes;
public XmlNodeWrapper(XmlNode node)
{
_node = node;
}
public object WrappedNode => _node;
public object? WrappedNode => _node;
public XmlNodeType NodeType => _node.NodeType;
public virtual string LocalName => _node.LocalName;
public virtual string? LocalName => _node.LocalName;
public List<IXmlNode> ChildNodes
{
@@ -309,7 +310,7 @@ namespace Newtonsoft.Json.Converters
}
}
public IXmlNode ParentNode
public IXmlNode? ParentNode
{
get
{
@@ -324,7 +325,7 @@ namespace Newtonsoft.Json.Converters
}
}
public string Value
public string? Value
{
get => _node.Value;
set => _node.Value = value;
@@ -340,7 +341,7 @@ namespace Newtonsoft.Json.Converters
return newChild;
}
public string NamespaceUri => _node.NamespaceURI;
public string? NamespaceUri => _node.NamespaceURI;
}
#endif
#endregion
@@ -348,22 +349,22 @@ namespace Newtonsoft.Json.Converters
#region Interfaces
internal interface IXmlDocument : IXmlNode
{
IXmlNode CreateComment(string text);
IXmlNode CreateTextNode(string text);
IXmlNode CreateCDataSection(string data);
IXmlNode CreateWhitespace(string text);
IXmlNode CreateSignificantWhitespace(string text);
IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone);
IXmlNode CreateComment(string? text);
IXmlNode CreateTextNode(string? text);
IXmlNode CreateCDataSection(string? data);
IXmlNode CreateWhitespace(string? text);
IXmlNode CreateSignificantWhitespace(string? text);
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; }
IXmlElement? DocumentElement { get; }
}
internal interface IXmlDeclaration : IXmlNode
@@ -391,14 +392,14 @@ namespace Newtonsoft.Json.Converters
internal interface IXmlNode
{
XmlNodeType NodeType { get; }
string LocalName { get; }
string? LocalName { get; }
List<IXmlNode> ChildNodes { get; }
List<IXmlNode> Attributes { get; }
IXmlNode ParentNode { get; }
string Value { get; set; }
IXmlNode? ParentNode { get; }
string? Value { get; set; }
IXmlNode AppendChild(IXmlNode newChild);
string NamespaceUri { get; }
object WrappedNode { get; }
string? NamespaceUri { get; }
object? WrappedNode { get; }
}
#endregion
@@ -449,12 +450,12 @@ namespace Newtonsoft.Json.Converters
public string InternalSubset => _documentType.InternalSubset;
public override string LocalName => "DOCTYPE";
public override string? LocalName => "DOCTYPE";
}
internal class XDocumentWrapper : XContainerWrapper, IXmlDocument
{
private XDocument Document => (XDocument)WrappedNode;
private XDocument Document => (XDocument)WrappedNode!;
public XDocumentWrapper(XDocument document)
: base(document)
@@ -488,42 +489,42 @@ namespace Newtonsoft.Json.Converters
}
}
public IXmlNode CreateComment(string text)
public IXmlNode CreateComment(string? text)
{
return new XObjectWrapper(new XComment(text));
}
public IXmlNode CreateTextNode(string text)
public IXmlNode CreateTextNode(string? text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateCDataSection(string data)
public IXmlNode CreateCDataSection(string? data)
{
return new XObjectWrapper(new XCData(data));
}
public IXmlNode CreateWhitespace(string text)
public IXmlNode CreateWhitespace(string? text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateSignificantWhitespace(string text)
public IXmlNode CreateSignificantWhitespace(string? 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));
}
@@ -539,18 +540,18 @@ 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));
}
public IXmlElement DocumentElement
public IXmlElement? DocumentElement
{
get
{
@@ -579,20 +580,20 @@ namespace Newtonsoft.Json.Converters
internal class XTextWrapper : XObjectWrapper
{
private XText Text => (XText)WrappedNode;
private XText Text => (XText)WrappedNode!;
public XTextWrapper(XText text)
: base(text)
{
}
public override string Value
public override string? Value
{
get => Text.Value;
set => Text.Value = value;
}
public override IXmlNode ParentNode
public override IXmlNode? ParentNode
{
get
{
@@ -608,20 +609,20 @@ namespace Newtonsoft.Json.Converters
internal class XCommentWrapper : XObjectWrapper
{
private XComment Text => (XComment)WrappedNode;
private XComment Text => (XComment)WrappedNode!;
public XCommentWrapper(XComment text)
: base(text)
{
}
public override string Value
public override string? Value
{
get => Text.Value;
set => Text.Value = value;
}
public override IXmlNode ParentNode
public override IXmlNode? ParentNode
{
get
{
@@ -637,16 +638,16 @@ namespace Newtonsoft.Json.Converters
internal class XProcessingInstructionWrapper : XObjectWrapper
{
private XProcessingInstruction ProcessingInstruction => (XProcessingInstruction)WrappedNode;
private XProcessingInstruction ProcessingInstruction => (XProcessingInstruction)WrappedNode!;
public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction)
: base(processingInstruction)
{
}
public override string LocalName => ProcessingInstruction.Target;
public override string? LocalName => ProcessingInstruction.Target;
public override string Value
public override string? Value
{
get => ProcessingInstruction.Data;
set => ProcessingInstruction.Data = value;
@@ -655,9 +656,9 @@ namespace Newtonsoft.Json.Converters
internal class XContainerWrapper : XObjectWrapper
{
private List<IXmlNode> _childNodes;
private List<IXmlNode>? _childNodes;
private XContainer Container => (XContainer)WrappedNode;
private XContainer Container => (XContainer)WrappedNode!;
public XContainerWrapper(XContainer container)
: base(container)
@@ -692,7 +693,7 @@ namespace Newtonsoft.Json.Converters
protected virtual bool HasChildNodes => Container.LastNode != null;
public override IXmlNode ParentNode
public override IXmlNode? ParentNode
{
get
{
@@ -761,26 +762,26 @@ namespace Newtonsoft.Json.Converters
internal class XObjectWrapper : IXmlNode
{
private readonly XObject _xmlObject;
private readonly XObject? _xmlObject;
public XObjectWrapper(XObject xmlObject)
public XObjectWrapper(XObject? xmlObject)
{
_xmlObject = xmlObject;
}
public object WrappedNode => _xmlObject;
public object? WrappedNode => _xmlObject;
public virtual XmlNodeType NodeType => _xmlObject.NodeType;
public virtual XmlNodeType NodeType => _xmlObject?.NodeType ?? XmlNodeType.None;
public virtual string LocalName => null;
public virtual string? LocalName => null;
public virtual List<IXmlNode> ChildNodes => XmlNodeConverter.EmptyChildNodes;
public virtual List<IXmlNode> Attributes => XmlNodeConverter.EmptyChildNodes;
public virtual IXmlNode ParentNode => null;
public virtual IXmlNode? ParentNode => null;
public virtual string Value
public virtual string? Value
{
get => null;
set => throw new InvalidOperationException();
@@ -791,29 +792,29 @@ namespace Newtonsoft.Json.Converters
throw new InvalidOperationException();
}
public virtual string NamespaceUri => null;
public virtual string? NamespaceUri => null;
}
internal class XAttributeWrapper : XObjectWrapper
{
private XAttribute Attribute => (XAttribute)WrappedNode;
private XAttribute Attribute => (XAttribute)WrappedNode!;
public XAttributeWrapper(XAttribute attribute)
: base(attribute)
{
}
public override string Value
public override string? Value
{
get => Attribute.Value;
set => Attribute.Value = value;
}
public override string LocalName => Attribute.Name.LocalName;
public override string? LocalName => Attribute.Name.LocalName;
public override string NamespaceUri => Attribute.Name.NamespaceName;
public override string? NamespaceUri => Attribute.Name.NamespaceName;
public override IXmlNode ParentNode
public override IXmlNode? ParentNode
{
get
{
@@ -829,9 +830,9 @@ namespace Newtonsoft.Json.Converters
internal class XElementWrapper : XContainerWrapper, IXmlElement
{
private List<IXmlNode> _attributes;
private List<IXmlNode>? _attributes;
private XElement Element => (XElement)WrappedNode;
private XElement Element => (XElement)WrappedNode!;
public XElementWrapper(XElement element)
: base(element)
@@ -853,7 +854,7 @@ namespace Newtonsoft.Json.Converters
// cache results to prevent multiple reads which kills perf in large documents
if (_attributes == null)
{
if (!Element.HasAttributes && !HasImplicitNamespaceAttribute(NamespaceUri))
if (!Element.HasAttributes && !HasImplicitNamespaceAttribute(NamespaceUri!))
{
_attributes = XmlNodeConverter.EmptyChildNodes;
}
@@ -867,7 +868,7 @@ namespace Newtonsoft.Json.Converters
// ensure elements created with a namespace but no namespace attribute are converted correctly
// e.g. new XElement("{http://example.com}MyElement");
string namespaceUri = NamespaceUri;
string namespaceUri = NamespaceUri!;
if (HasImplicitNamespaceAttribute(namespaceUri))
{
_attributes.Insert(0, new XAttributeWrapper(new XAttribute("xmlns", namespaceUri)));
@@ -915,15 +916,15 @@ namespace Newtonsoft.Json.Converters
return result;
}
public override string Value
public override string? Value
{
get => Element.Value;
set => Element.Value = value;
}
public override string LocalName => Element.Name.LocalName;
public override string? LocalName => Element.Name.LocalName;
public override string NamespaceUri => Element.Name.NamespaceName;
public override string? NamespaceUri => Element.Name.NamespaceName;
public string GetPrefixOfNamespace(string namespaceUri)
{
@@ -954,7 +955,7 @@ namespace Newtonsoft.Json.Converters
/// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produced multiple root elements.
/// </summary>
/// <value>The name of the deserialized root element.</value>
public string DeserializeRootElementName { get; set; }
public string? DeserializeRootElementName { get; set; }
/// <summary>
/// Gets or sets a value to indicate whether to write the Json.NET array attribute.
@@ -985,7 +986,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="serializer">The calling serializer.</param>
/// <param name="value">The value.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
@@ -1031,9 +1032,9 @@ namespace Newtonsoft.Json.Converters
private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager)
{
List<IXmlNode> parentElements = null;
List<IXmlNode>? parentElements = null;
IXmlNode parent = node;
IXmlNode? parent = node;
while ((parent = parent.ParentNode) != null)
{
if (parent.NodeType == XmlNodeType.Element)
@@ -1067,7 +1068,7 @@ namespace Newtonsoft.Json.Converters
private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager)
{
string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/"))
string? prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/"))
? null
: manager.LookupPrefix(node.NamespaceUri);
@@ -1160,9 +1161,9 @@ namespace Newtonsoft.Json.Converters
// value of dictionary will be a single IXmlNode when there is one for a name,
// or a List<IXmlNode> when there are multiple
Dictionary<string, object> nodesGroupedByName = null;
Dictionary<string, object>? nodesGroupedByName = null;
string nodeName = null;
string? nodeName = null;
for (int i = 0; i < node.ChildNodes.Count; i++)
{
@@ -1208,7 +1209,7 @@ namespace Newtonsoft.Json.Converters
{
if (!(value is List<IXmlNode> nodes))
{
nodes = new List<IXmlNode> {(IXmlNode)value};
nodes = new List<IXmlNode> {(IXmlNode)value!};
nodesGroupedByName[currentNodeName] = nodes;
}
@@ -1219,7 +1220,7 @@ namespace Newtonsoft.Json.Converters
if (nodesGroupedByName == null)
{
WriteGroupedNodes(writer, manager, writePropertyName, node.ChildNodes, nodeName);
WriteGroupedNodes(writer, manager, writePropertyName, node.ChildNodes, nodeName!);
}
else
{
@@ -1315,7 +1316,11 @@ namespace Newtonsoft.Json.Converters
string namespacePrefix = (attribute.LocalName != "xmlns")
? XmlConvert.DecodeName(attribute.LocalName)
: string.Empty;
string namespaceUri = attribute.Value;
string? namespaceUri = attribute.Value;
if (namespaceUri == null)
{
throw new JsonSerializationException("Namespace attribute must have a value.");
}
manager.AddNamespace(namespacePrefix, namespaceUri);
}
@@ -1473,7 +1478,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
@@ -1486,8 +1491,8 @@ namespace Newtonsoft.Json.Converters
}
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
IXmlDocument document = null;
IXmlNode rootNode = null;
IXmlDocument? document = null;
IXmlNode? rootNode = null;
#if HAVE_XLINQ
if (typeof(XObject).IsAssignableFrom(objectType))
@@ -1545,7 +1550,7 @@ namespace Newtonsoft.Json.Converters
#if HAVE_XLINQ
if (objectType == typeof(XElement))
{
XElement element = (XElement)document.DocumentElement.WrappedNode;
XElement element = (XElement)document.DocumentElement!.WrappedNode!;
element.Remove();
return element;
@@ -1554,7 +1559,7 @@ namespace Newtonsoft.Json.Converters
#if HAVE_XML_DOCUMENT
if (objectType == typeof(XmlElement))
{
return document.DocumentElement.WrappedNode;
return document.DocumentElement!.WrappedNode;
}
#endif
@@ -1616,8 +1621,8 @@ namespace Newtonsoft.Json.Converters
throw JsonSerializationException.Create(reader, "XmlNodeConverter cannot convert JSON with an empty property name to XML.");
}
Dictionary<string, string> attributeNameValues = null;
string elementPrefix = null;
Dictionary<string, string?>? attributeNameValues = null;
string? elementPrefix = null;
if (!EncodeSpecialCharacters)
{
@@ -1629,7 +1634,7 @@ namespace Newtonsoft.Json.Converters
if (propertyName.StartsWith('@'))
{
string attributeName = propertyName.Substring(1);
string attributePrefix = MiscellaneousUtils.GetPrefix(attributeName);
string? attributePrefix = MiscellaneousUtils.GetPrefix(attributeName);
AddAttribute(reader, document, currentNode, propertyName, attributeName, manager, attributePrefix);
return;
@@ -1666,7 +1671,7 @@ namespace Newtonsoft.Json.Converters
CreateElement(reader, document, currentNode, propertyName, manager, elementPrefix, attributeNameValues);
}
private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string elementName, XmlNamespaceManager manager, string elementPrefix, Dictionary<string, string> attributeNameValues)
private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string elementName, XmlNamespaceManager manager, string? elementPrefix, Dictionary<string, string?>? attributeNameValues)
{
IXmlElement element = CreateElement(elementName, document, elementPrefix, manager);
@@ -1675,10 +1680,10 @@ namespace Newtonsoft.Json.Converters
if (attributeNameValues != null)
{
// add attributes to newly created element
foreach (KeyValuePair<string, string> nameValue in attributeNameValues)
foreach (KeyValuePair<string, string?> nameValue in attributeNameValues)
{
string encodedName = XmlConvert.EncodeName(nameValue.Key);
string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key);
string? attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key);
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value) : document.CreateAttribute(encodedName, nameValue.Value);
@@ -1694,7 +1699,7 @@ namespace Newtonsoft.Json.Converters
case JsonToken.Boolean:
case JsonToken.Date:
case JsonToken.Bytes:
string text = ConvertTokenToXmlValue(reader);
string? text = ConvertTokenToXmlValue(reader);
if (text != null)
{
element.AppendChild(document.CreateTextNode(text));
@@ -1718,7 +1723,7 @@ namespace Newtonsoft.Json.Converters
}
}
private static void AddAttribute(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, string attributeName, XmlNamespaceManager manager, string attributePrefix)
private static void AddAttribute(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, string attributeName, XmlNamespaceManager manager, string? attributePrefix)
{
if (currentNode.NodeType == XmlNodeType.Document)
{
@@ -1726,7 +1731,7 @@ namespace Newtonsoft.Json.Converters
}
string encodedName = XmlConvert.EncodeName(attributeName);
string attributeValue = ConvertTokenToXmlValue(reader);
string? attributeValue = ConvertTokenToXmlValue(reader);
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix), attributeValue)
@@ -1735,7 +1740,7 @@ namespace Newtonsoft.Json.Converters
((IXmlElement)currentNode).SetAttributeNode(attribute);
}
private static string ConvertTokenToXmlValue(JsonReader reader)
private static string? ConvertTokenToXmlValue(JsonReader reader)
{
switch (reader.TokenType)
{
@@ -1782,7 +1787,7 @@ namespace Newtonsoft.Json.Converters
#endif
}
case JsonToken.Bytes:
return Convert.ToBase64String((byte[])reader.Value);
return Convert.ToBase64String((byte[])reader.Value!);
case JsonToken.Null:
return null;
default:
@@ -1792,7 +1797,7 @@ namespace Newtonsoft.Json.Converters
private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager)
{
string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
string? elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager);
@@ -1858,9 +1863,9 @@ namespace Newtonsoft.Json.Converters
return true;
}
private Dictionary<string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager)
private Dictionary<string, string?>? ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager)
{
Dictionary<string, string> attributeNameValues = null;
Dictionary<string, string?>? attributeNameValues = null;
bool finished = false;
// read properties until first non-attribute is encountered
@@ -1869,19 +1874,19 @@ namespace Newtonsoft.Json.Converters
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string attributeName = reader.Value.ToString();
string attributeName = reader.Value!.ToString();
if (!string.IsNullOrEmpty(attributeName))
{
char firstChar = attributeName[0];
string attributeValue;
string? attributeValue;
switch (firstChar)
{
case '@':
if (attributeNameValues == null)
{
attributeNameValues = new Dictionary<string, string>();
attributeNameValues = new Dictionary<string, string?>();
}
attributeName = attributeName.Substring(1);
@@ -1889,7 +1894,7 @@ namespace Newtonsoft.Json.Converters
attributeValue = ConvertTokenToXmlValue(reader);
attributeNameValues.Add(attributeName, attributeValue);
if (IsNamespaceAttribute(attributeName, out string namespacePrefix))
if (IsNamespaceAttribute(attributeName, out string? namespacePrefix))
{
manager.AddNamespace(namespacePrefix, attributeValue);
}
@@ -1909,7 +1914,7 @@ namespace Newtonsoft.Json.Converters
{
if (attributeNameValues == null)
{
attributeNameValues = new Dictionary<string, string>();
attributeNameValues = new Dictionary<string, string?>();
}
// ensure that the prefix used is free
@@ -1941,7 +1946,7 @@ namespace Newtonsoft.Json.Converters
if (attributeNameValues == null)
{
attributeNameValues = new Dictionary<string, string>();
attributeNameValues = new Dictionary<string, string?>();
}
attributeValue = reader.Value?.ToString();
@@ -1979,12 +1984,12 @@ namespace Newtonsoft.Json.Converters
{
if (propertyName == DeclarationName)
{
string version = null;
string encoding = null;
string standalone = null;
string? version = null;
string? encoding = null;
string? standalone = null;
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
switch (reader.Value.ToString())
switch (reader.Value?.ToString())
{
case "@version":
reader.ReadAndAssert();
@@ -2016,13 +2021,13 @@ namespace Newtonsoft.Json.Converters
#if HAVE_XML_DOCUMENT_TYPE
private void CreateDocumentType(JsonReader reader, IXmlDocument document, IXmlNode currentNode)
{
string name = null;
string publicId = null;
string systemId = null;
string internalSubset = null;
string? name = null;
string? publicId = null;
string? systemId = null;
string? internalSubset = null;
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
switch (reader.Value.ToString())
switch (reader.Value?.ToString())
{
case "@name":
reader.ReadAndAssert();
@@ -2050,7 +2055,7 @@ namespace Newtonsoft.Json.Converters
}
#endif
private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager)
private IXmlElement CreateElement(string elementName, IXmlDocument document, string? elementPrefix, XmlNamespaceManager manager)
{
string encodeName = EncodeSpecialCharacters ? XmlConvert.EncodeLocalName(elementName) : XmlConvert.EncodeName(elementName);
string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix);
@@ -2072,7 +2077,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)
@@ -2086,7 +2091,7 @@ namespace Newtonsoft.Json.Converters
if (count == 1 && WriteArrayAttribute)
{
MiscellaneousUtils.GetQualifiedNameParts(propertyName, out string elementPrefix, out string localName);
MiscellaneousUtils.GetQualifiedNameParts(propertyName, out string? elementPrefix, out string localName);
string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix);
foreach (IXmlNode childNode in currentNode.ChildNodes)
@@ -2105,7 +2110,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)
{
@@ -2113,7 +2118,7 @@ namespace Newtonsoft.Json.Converters
}
break;
case JsonToken.Comment:
currentNode.AppendChild(document.CreateComment((string)reader.Value));
currentNode.AppendChild(document.CreateComment((string)reader.Value!));
break;
case JsonToken.EndObject:
case JsonToken.EndArray:
@@ -2131,7 +2136,7 @@ namespace Newtonsoft.Json.Converters
/// <param name="attributeName">Attribute name to test.</param>
/// <param name="prefix">The attribute name prefix if it has one, otherwise an empty string.</param>
/// <returns><c>true</c> if attribute name is for a namespace attribute, otherwise <c>false</c>.</returns>
private bool IsNamespaceAttribute(string attributeName, out string prefix)
private bool IsNamespaceAttribute(string attributeName, [NotNullWhen(true)]out string? prefix)
{
if (attributeName.StartsWith("xmlns", StringComparison.Ordinal))
{
+1 -1
View File
@@ -59,7 +59,7 @@ namespace Newtonsoft.Json
/// <param name="start">The zero-based index into the array specifying the first character of the name.</param>
/// <param name="length">The number of characters in the name.</param>
/// <returns>A string containing the same characters as the specified range of characters in the given array.</returns>
public override string Get(char[] key, int start, int length)
public override string? Get(char[] key, int start, int length)
{
if (length == 0)
{
+1 -1
View File
@@ -17,6 +17,6 @@
/// Return an array to the pool.
/// </summary>
/// <param name="array">The array that is being returned.</param>
void Return(T[] array);
void Return(T[]? array);
}
}
+10 -10
View File
@@ -38,25 +38,25 @@ namespace Newtonsoft.Json
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>The title.</value>
public string Title { get; set; }
public string? Title { get; set; }
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>The description.</value>
public string Description { get; set; }
public string? Description { get; set; }
/// <summary>
/// Gets or sets the collection's items converter.
/// </summary>
/// <value>The collection's items converter.</value>
public Type ItemConverterType { get; set; }
public Type? ItemConverterType { get; set; }
/// <summary>
/// The parameter list to use when constructing the <see cref="JsonConverter"/> described by <see cref="ItemConverterType"/>.
@@ -69,13 +69,13 @@ namespace Newtonsoft.Json
/// [JsonContainer(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })]
/// </code>
/// </example>
public object[] ItemConverterParameters { get; set; }
public object[]? ItemConverterParameters { get; set; }
/// <summary>
/// Gets or sets the <see cref="Type"/> of the <see cref="NamingStrategy"/>.
/// </summary>
/// <value>The <see cref="Type"/> of the <see cref="NamingStrategy"/>.</value>
public Type NamingStrategyType
public Type? NamingStrategyType
{
get => _namingStrategyType;
set
@@ -96,7 +96,7 @@ namespace Newtonsoft.Json
/// [JsonContainer(NamingStrategyType = typeof(MyNamingStrategy), NamingStrategyParameters = new object[] { 123, "Four" })]
/// </code>
/// </example>
public object[] NamingStrategyParameters
public object[]? NamingStrategyParameters
{
get => _namingStrategyParameters;
set
@@ -106,7 +106,7 @@ namespace Newtonsoft.Json
}
}
internal NamingStrategy NamingStrategyInstance { get; set; }
internal NamingStrategy? NamingStrategyInstance { get; set; }
// yuck. can't set nullable properties on an attribute in C#
// have to use this approach to get an unset default state
@@ -114,8 +114,8 @@ namespace Newtonsoft.Json
internal bool? _itemIsReference;
internal ReferenceLoopHandling? _itemReferenceLoopHandling;
internal TypeNameHandling? _itemTypeNameHandling;
private Type _namingStrategyType;
private object[] _namingStrategyParameters;
private Type? _namingStrategyType;
private object[]? _namingStrategyParameters;
/// <summary>
/// Gets or sets a value that indicates whether to preserve object references.
+53 -46
View File
@@ -36,9 +36,10 @@ using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System.Text;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
#if HAVE_XLINQ
using System.Xml.Linq;
#endif
namespace Newtonsoft.Json
@@ -395,7 +396,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Uri"/>.</returns>
public static string ToString(Uri value)
public static string ToString(Uri? value)
{
if (value == null)
{
@@ -415,7 +416,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value)
public static string ToString(string? value)
{
return ToString(value, '"');
}
@@ -426,7 +427,7 @@ namespace Newtonsoft.Json
/// <param name="value">The value to convert.</param>
/// <param name="delimiter">The string delimiter character.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimiter)
public static string ToString(string? value, char delimiter)
{
return ToString(value, delimiter, StringEscapeHandling.Default);
}
@@ -438,7 +439,7 @@ namespace Newtonsoft.Json
/// <param name="delimiter">The string delimiter character.</param>
/// <param name="stringEscapeHandling">The string escape handling.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimiter, StringEscapeHandling stringEscapeHandling)
public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling)
{
if (delimiter != '"' && delimiter != '\'')
{
@@ -453,7 +454,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
public static string ToString(object value)
public static string ToString(object? value)
{
if (value == null)
{
@@ -524,9 +525,9 @@ namespace Newtonsoft.Json
/// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object value)
public static string SerializeObject(object? value)
{
return SerializeObject(value, null, (JsonSerializerSettings)null);
return SerializeObject(value, null, (JsonSerializerSettings?)null);
}
/// <summary>
@@ -538,9 +539,9 @@ namespace Newtonsoft.Json
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting)
public static string SerializeObject(object? value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings)null);
return SerializeObject(value, formatting, (JsonSerializerSettings?)null);
}
/// <summary>
@@ -550,9 +551,9 @@ namespace Newtonsoft.Json
/// <param name="converters">A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, params JsonConverter[] converters)
public static string SerializeObject(object? value, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
JsonSerializerSettings? settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
@@ -567,9 +568,9 @@ namespace Newtonsoft.Json
/// <param name="converters">A collection of converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
JsonSerializerSettings? settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
@@ -586,7 +587,7 @@ namespace Newtonsoft.Json
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, JsonSerializerSettings settings)
public static string SerializeObject(object? value, JsonSerializerSettings settings)
{
return SerializeObject(value, null, settings);
}
@@ -606,7 +607,7 @@ namespace Newtonsoft.Json
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Type type, JsonSerializerSettings settings)
public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
@@ -624,7 +625,7 @@ namespace Newtonsoft.Json
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings)
{
return SerializeObject(value, null, formatting, settings);
}
@@ -645,7 +646,7 @@ namespace Newtonsoft.Json
/// A JSON string representation of the object.
/// </returns>
[DebuggerStepThrough]
public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings)
public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
jsonSerializer.Formatting = formatting;
@@ -653,7 +654,7 @@ namespace Newtonsoft.Json
return SerializeObjectInternal(value, type, jsonSerializer);
}
private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer)
private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer)
{
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
@@ -675,9 +676,9 @@ namespace Newtonsoft.Json
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value)
public static object? DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings)null);
return DeserializeObject(value, null, (JsonSerializerSettings?)null);
}
/// <summary>
@@ -690,7 +691,7 @@ namespace Newtonsoft.Json
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value, JsonSerializerSettings settings)
public static object? DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
@@ -702,9 +703,9 @@ namespace Newtonsoft.Json
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value, Type type)
public static object? DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings)null);
return DeserializeObject(value, type, (JsonSerializerSettings?)null);
}
/// <summary>
@@ -716,7 +717,7 @@ namespace Newtonsoft.Json
[DebuggerStepThrough]
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings)null);
return DeserializeObject<T>(value, (JsonSerializerSettings?)null);
}
/// <summary>
@@ -765,9 +766,12 @@ namespace Newtonsoft.Json
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
[return: MaybeNull]
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
#pragma warning disable CS8601 // Possible null reference assignment.
return (T)DeserializeObject(value, typeof(T), converters);
#pragma warning restore CS8601 // Possible null reference assignment.
}
/// <summary>
@@ -781,9 +785,12 @@ namespace Newtonsoft.Json
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
[return: MaybeNull]
public static T DeserializeObject<T>(string value, JsonSerializerSettings? settings)
{
#pragma warning disable CS8601 // Possible null reference assignment.
return (T)DeserializeObject(value, typeof(T), settings);
#pragma warning restore CS8601 // Possible null reference assignment.
}
/// <summary>
@@ -794,9 +801,9 @@ namespace Newtonsoft.Json
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
[DebuggerStepThrough]
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
JsonSerializerSettings? settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
@@ -813,7 +820,7 @@ namespace Newtonsoft.Json
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
@@ -853,7 +860,7 @@ namespace Newtonsoft.Json
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is <c>null</c>, default serialization settings will be used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
public static void PopulateObject(string value, object target, JsonSerializerSettings? settings)
{
JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
@@ -882,7 +889,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode node)
public static string SerializeXmlNode(XmlNode? node)
{
return SerializeXmlNode(node, Formatting.None);
}
@@ -893,7 +900,7 @@ namespace Newtonsoft.Json
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting)
public static string SerializeXmlNode(XmlNode? node, Formatting formatting)
{
XmlNodeConverter converter = new XmlNodeConverter();
@@ -907,7 +914,7 @@ namespace Newtonsoft.Json
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the <see cref="XmlNode"/>.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject)
public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
@@ -919,7 +926,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value)
public static XmlDocument? DeserializeXmlNode(string value)
{
return DeserializeXmlNode(value, null);
}
@@ -930,7 +937,7 @@ namespace Newtonsoft.Json
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName)
public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName)
{
return DeserializeXmlNode(value, deserializeRootElementName, false);
}
@@ -946,7 +953,7 @@ namespace Newtonsoft.Json
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
{
return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
@@ -968,14 +975,14 @@ namespace Newtonsoft.Json
/// as part of the XML element name.
/// </param>
/// <returns>The deserialized <see cref="XmlNode"/>.</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
converter.EncodeSpecialCharacters = encodeSpecialCharacters;
return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter);
return (XmlDocument?)DeserializeObject(value, typeof(XmlDocument), converter);
}
#endif
@@ -985,7 +992,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject node)
public static string SerializeXNode(XObject? node)
{
return SerializeXNode(node, Formatting.None);
}
@@ -996,7 +1003,7 @@ namespace Newtonsoft.Json
/// <param name="node">The node to convert to JSON.</param>
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject node, Formatting formatting)
public static string SerializeXNode(XObject? node, Formatting formatting)
{
return SerializeXNode(node, formatting, false);
}
@@ -1008,7 +1015,7 @@ namespace Newtonsoft.Json
/// <param name="formatting">Indicates how the output should be formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the <see cref="XNode"/>.</returns>
public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject)
public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
@@ -1020,7 +1027,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value)
public static XDocument? DeserializeXNode(string value)
{
return DeserializeXNode(value, null);
}
@@ -1031,7 +1038,7 @@ namespace Newtonsoft.Json
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName)
public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName)
{
return DeserializeXNode(value, deserializeRootElementName, false);
}
@@ -1047,7 +1054,7 @@ namespace Newtonsoft.Json
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
{
return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, false);
}
@@ -1069,14 +1076,14 @@ namespace Newtonsoft.Json
/// as part of the XML element name.
/// </param>
/// <returns>The deserialized <see cref="XNode"/>.</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
converter.EncodeSpecialCharacters = encodeSpecialCharacters;
return (XDocument)DeserializeObject(value, typeof(XDocument), converter);
return (XDocument?)DeserializeObject(value, typeof(XDocument), converter);
}
#endif
#endregion
+12 -6
View File
@@ -26,6 +26,8 @@
using System;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
namespace Newtonsoft.Json
{
@@ -40,7 +42,7 @@ namespace Newtonsoft.Json
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public abstract void WriteJson(JsonWriter writer, object value, JsonSerializer serializer);
public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer);
/// <summary>
/// Reads the JSON representation of the object.
@@ -50,7 +52,7 @@ namespace Newtonsoft.Json
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public abstract object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer);
public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer);
/// <summary>
/// Determines whether this instance can convert the specified object type.
@@ -86,13 +88,15 @@ namespace Newtonsoft.Json
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public sealed override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (!(value != null ? value is T : ReflectionUtils.IsNullable(typeof(T))))
{
throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
}
#pragma warning disable CS8601 // Possible null reference assignment.
WriteJson(writer, (T)value, serializer);
#pragma warning restore CS8601 // Possible null reference assignment.
}
/// <summary>
@@ -101,7 +105,7 @@ namespace Newtonsoft.Json
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public abstract void WriteJson(JsonWriter writer, T value, JsonSerializer serializer);
public abstract void WriteJson(JsonWriter writer, [AllowNull]T value, JsonSerializer serializer);
/// <summary>
/// Reads the JSON representation of the object.
@@ -111,14 +115,16 @@ namespace Newtonsoft.Json
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public sealed override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
bool existingIsNull = existingValue == null;
if (!(existingIsNull || existingValue is T))
{
throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
}
#pragma warning disable CS8601 // Possible null reference assignment.
return ReadJson(reader, objectType, existingIsNull ? default : (T)existingValue, !existingIsNull, serializer);
#pragma warning restore CS8601 // Possible null reference assignment.
}
/// <summary>
@@ -130,7 +136,7 @@ namespace Newtonsoft.Json
/// <param name="hasExistingValue">The existing value has a value.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public abstract T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer);
public abstract T ReadJson(JsonReader reader, Type objectType, [AllowNull]T existingValue, bool hasExistingValue, JsonSerializer serializer);
/// <summary>
/// Determines whether this instance can convert the specified object type.
@@ -47,7 +47,7 @@ namespace Newtonsoft.Json
/// The parameter list to use when constructing the <see cref="JsonConverter"/> described by <see cref="ConverterType"/>.
/// If <c>null</c>, the default constructor is used.
/// </summary>
public object[] ConverterParameters { get; }
public object[]? ConverterParameters { get; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonConverterAttribute"/> class.
+1 -1
View File
@@ -63,7 +63,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or <c>null</c> if no inner exception is specified.</param>
public JsonException(string message, Exception innerException)
public JsonException(string message, Exception? innerException)
: base(message, innerException)
{
}
+1 -1
View File
@@ -12,6 +12,6 @@
/// <param name="start">The zero-based index into the array specifying the first character of the name.</param>
/// <param name="length">The number of characters in the name.</param>
/// <returns>A string containing the same characters as the specified range of characters in the given array.</returns>
public abstract string Get(char[] key, int start, int length);
public abstract string? Get(char[] key, int start, int length);
}
}
+7 -7
View File
@@ -46,7 +46,7 @@ namespace Newtonsoft.Json
internal JsonContainerType Type;
internal int Position;
internal string PropertyName;
internal string? PropertyName;
internal bool HasIndex;
public JsonPosition(JsonContainerType type)
@@ -62,7 +62,7 @@ namespace Newtonsoft.Json
switch (Type)
{
case JsonContainerType.Object:
return PropertyName.Length + 5;
return PropertyName!.Length + 5;
case JsonContainerType.Array:
case JsonContainerType.Constructor:
return MathUtils.IntLength((ulong)Position) + 2;
@@ -71,12 +71,12 @@ namespace Newtonsoft.Json
}
}
internal void WriteTo(StringBuilder sb, ref StringWriter writer, ref char[] buffer)
internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer)
{
switch (Type)
{
case JsonContainerType.Object:
string propertyName = PropertyName;
string propertyName = PropertyName!;
if (propertyName.IndexOfAny(SpecialCharacters) != -1)
{
sb.Append(@"['");
@@ -130,8 +130,8 @@ namespace Newtonsoft.Json
}
StringBuilder sb = new StringBuilder(capacity);
StringWriter writer = null;
char[] buffer = null;
StringWriter? writer = null;
char[]? buffer = null;
if (positions != null)
{
foreach (JsonPosition state in positions)
@@ -147,7 +147,7 @@ namespace Newtonsoft.Json
return sb.ToString();
}
internal static string FormatMessage(IJsonLineInfo lineInfo, string path, string message)
internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message)
{
// don't add a fullstop and space when message ends with a new line
if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
+5 -5
View File
@@ -52,7 +52,7 @@ namespace Newtonsoft.Json
/// Gets or sets the <see cref="JsonConverter"/> type used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items <see cref="JsonConverter"/> type.</value>
public Type ItemConverterType { get; set; }
public Type? ItemConverterType { get; set; }
/// <summary>
/// The parameter list to use when constructing the <see cref="JsonConverter"/> described by <see cref="ItemConverterType"/>.
@@ -65,13 +65,13 @@ namespace Newtonsoft.Json
/// [JsonProperty(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })]
/// </code>
/// </example>
public object[] ItemConverterParameters { get; set; }
public object[]? ItemConverterParameters { get; set; }
/// <summary>
/// Gets or sets the <see cref="Type"/> of the <see cref="NamingStrategy"/>.
/// </summary>
/// <value>The <see cref="Type"/> of the <see cref="NamingStrategy"/>.</value>
public Type NamingStrategyType { get; set; }
public Type? NamingStrategyType { get; set; }
/// <summary>
/// The parameter list to use when constructing the <see cref="NamingStrategy"/> described by <see cref="JsonPropertyAttribute.NamingStrategyType"/>.
@@ -84,7 +84,7 @@ namespace Newtonsoft.Json
/// [JsonProperty(NamingStrategyType = typeof(MyNamingStrategy), NamingStrategyParameters = new object[] { 123, "Four" })]
/// </code>
/// </example>
public object[] NamingStrategyParameters { get; set; }
public object[]? NamingStrategyParameters { get; set; }
/// <summary>
/// Gets or sets the null value handling used when serializing this property.
@@ -172,7 +172,7 @@ namespace Newtonsoft.Json
/// Gets or sets the name of the property.
/// </summary>
/// <value>The name of the property.</value>
public string PropertyName { get; set; }
public string? PropertyName { get; set; }
/// <summary>
/// Gets or sets the reference loop handling used when serializing the property's collection items.
+5 -5
View File
@@ -101,12 +101,12 @@ namespace Newtonsoft.Json
/// property returns the <see cref="byte"/>[]. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task<byte[]> ReadAsBytesAsync(CancellationToken cancellationToken = default)
public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default)
{
return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes());
return cancellationToken.CancelIfRequestedAsync<byte[]?>() ?? Task.FromResult(ReadAsBytes());
}
internal async Task<byte[]> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken)
internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken)
{
List<byte> buffer = new List<byte>();
@@ -199,9 +199,9 @@ namespace Newtonsoft.Json
/// property returns the <see cref="string"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task<string> ReadAsStringAsync(CancellationToken cancellationToken = default)
public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default)
{
return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString());
return cancellationToken.CancelIfRequestedAsync<string?>() ?? Task.FromResult(ReadAsString());
}
internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken)
+38 -39
View File
@@ -113,18 +113,18 @@ namespace Newtonsoft.Json
// current Token data
private JsonToken _tokenType;
private object _value;
private object? _value;
internal char _quoteChar;
internal State _currentState;
private JsonPosition _currentPosition;
private CultureInfo _culture;
private CultureInfo? _culture;
private DateTimeZoneHandling _dateTimeZoneHandling;
private int? _maxDepth;
private bool _hasExceededMaxDepth;
internal DateParseHandling _dateParseHandling;
internal FloatParseHandling _floatParseHandling;
private string _dateFormatString;
private List<JsonPosition> _stack;
private string? _dateFormatString;
private List<JsonPosition>? _stack;
/// <summary>
/// Gets the current reader state.
@@ -219,7 +219,7 @@ namespace Newtonsoft.Json
/// <summary>
/// Gets or sets how custom date formatted strings are parsed when reading JSON.
/// </summary>
public string DateFormatString
public string? DateFormatString
{
get => _dateFormatString;
set => _dateFormatString = value;
@@ -250,12 +250,12 @@ namespace Newtonsoft.Json
/// <summary>
/// Gets the text value of the current JSON token.
/// </summary>
public virtual object Value => _value;
public virtual object? Value => _value;
/// <summary>
/// Gets the .NET type for the current JSON token.
/// </summary>
public virtual Type ValueType => _value?.GetType();
public virtual Type? ValueType => _value?.GetType();
/// <summary>
/// Gets the depth of the current token in the JSON document.
@@ -295,7 +295,7 @@ namespace Newtonsoft.Json
JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null;
return JsonPosition.BuildPath(_stack, current);
return JsonPosition.BuildPath(_stack!, current);
}
}
@@ -408,7 +408,7 @@ namespace Newtonsoft.Json
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value;
object v = Value!;
if (v is int i)
{
return i;
@@ -436,14 +436,14 @@ namespace Newtonsoft.Json
SetToken(JsonToken.Integer, i, false);
return i;
case JsonToken.String:
string s = (string)Value;
string? s = (string?)Value;
return ReadInt32String(s);
}
throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal int? ReadInt32String(string s)
internal int? ReadInt32String(string? s)
{
if (string.IsNullOrEmpty(s))
{
@@ -467,7 +467,7 @@ namespace Newtonsoft.Json
/// Reads the next JSON token from the source as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual string ReadAsString()
public virtual string? ReadAsString()
{
JsonToken t = GetContentToken();
@@ -478,12 +478,12 @@ namespace Newtonsoft.Json
case JsonToken.EndArray:
return null;
case JsonToken.String:
return (string)Value;
return (string?)Value;
}
if (JsonTokenUtils.IsPrimitiveToken(t))
{
object v = Value;
object? v = Value;
if (v != null)
{
string s;
@@ -508,7 +508,7 @@ namespace Newtonsoft.Json
/// Reads the next JSON token from the source as a <see cref="Byte"/>[].
/// </summary>
/// <returns>A <see cref="Byte"/>[] or <c>null</c> if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns>
public virtual byte[] ReadAsBytes()
public virtual byte[]? ReadAsBytes()
{
JsonToken t = GetContentToken();
@@ -518,7 +518,7 @@ namespace Newtonsoft.Json
{
ReadIntoWrappedTypeObject();
byte[] data = ReadAsBytes();
byte[]? data = ReadAsBytes();
ReaderReadAndAssert();
if (TokenType != JsonToken.EndObject)
@@ -533,7 +533,7 @@ namespace Newtonsoft.Json
{
// attempt to convert possible base 64 or GUID string to bytes
// GUID has to have format 00000000-0000-0000-0000-000000000000
string s = (string)Value;
string s = (string)Value!;
byte[] data;
@@ -565,7 +565,7 @@ namespace Newtonsoft.Json
return data;
}
return (byte[])Value;
return (byte[]?)Value;
case JsonToken.StartArray:
return ReadArrayIntoByteArray();
}
@@ -627,7 +627,7 @@ namespace Newtonsoft.Json
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value;
object v = Value!;
if (v is double d)
{
return d;
@@ -648,13 +648,13 @@ namespace Newtonsoft.Json
return (double)d;
case JsonToken.String:
return ReadDoubleString((string)Value);
return ReadDoubleString((string?)Value);
}
throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal double? ReadDoubleString(string s)
internal double? ReadDoubleString(string? s)
{
if (string.IsNullOrEmpty(s))
{
@@ -705,15 +705,15 @@ namespace Newtonsoft.Json
SetToken(JsonToken.Boolean, b, false);
return b;
case JsonToken.String:
return ReadBooleanString((string)Value);
return ReadBooleanString((string?)Value);
case JsonToken.Boolean:
return (bool)Value;
return (bool)Value!;
}
throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal bool? ReadBooleanString(string s)
internal bool? ReadBooleanString(string? s)
{
if (string.IsNullOrEmpty(s))
{
@@ -749,7 +749,7 @@ namespace Newtonsoft.Json
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value;
object v = Value!;
if (v is decimal d)
{
@@ -778,13 +778,13 @@ namespace Newtonsoft.Json
SetToken(JsonToken.Float, d, false);
return d;
case JsonToken.String:
return ReadDecimalString((string)Value);
return ReadDecimalString((string?)Value);
}
throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal decimal? ReadDecimalString(string s)
internal decimal? ReadDecimalString(string? s)
{
if (string.IsNullOrEmpty(s))
{
@@ -830,16 +830,15 @@ namespace Newtonsoft.Json
}
#endif
return (DateTime)Value;
return (DateTime)Value!;
case JsonToken.String:
string s = (string)Value;
return ReadDateTimeString(s);
return ReadDateTimeString((string?)Value);
}
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
internal DateTime? ReadDateTimeString(string s)
internal DateTime? ReadDateTimeString(string? s)
{
if (string.IsNullOrEmpty(s))
{
@@ -885,16 +884,16 @@ namespace Newtonsoft.Json
SetToken(JsonToken.Date, new DateTimeOffset(time), false);
}
return (DateTimeOffset)Value;
return (DateTimeOffset)Value!;
case JsonToken.String:
string s = (string)Value;
string? s = (string?)Value;
return ReadDateTimeOffsetString(s);
default:
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
}
internal DateTimeOffset? ReadDateTimeOffsetString(string s)
internal DateTimeOffset? ReadDateTimeOffsetString(string? s)
{
if (string.IsNullOrEmpty(s))
{
@@ -985,7 +984,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
protected void SetToken(JsonToken newToken, object value)
protected void SetToken(JsonToken newToken, object? value)
{
SetToken(newToken, value, true);
}
@@ -996,7 +995,7 @@ namespace Newtonsoft.Json
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
/// <param name="updateIndex">A flag indicating whether the position index inside an array should be updated.</param>
protected void SetToken(JsonToken newToken, object value, bool updateIndex)
protected void SetToken(JsonToken newToken, object? value, bool updateIndex)
{
_tokenType = newToken;
_value = value;
@@ -1027,7 +1026,7 @@ namespace Newtonsoft.Json
case JsonToken.PropertyName:
_currentState = State.Property;
_currentPosition.PropertyName = (string)value;
_currentPosition.PropertyName = (string)value!;
break;
case JsonToken.Undefined:
case JsonToken.Integer:
@@ -1170,7 +1169,7 @@ namespace Newtonsoft.Json
}
}
internal void ReadForTypeAndAssert(JsonContract contract, bool hasConverter)
internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter)
{
if (!ReadForType(contract, hasConverter))
{
@@ -1178,7 +1177,7 @@ namespace Newtonsoft.Json
}
}
internal bool ReadForType(JsonContract contract, bool hasConverter)
internal bool ReadForType(JsonContract? contract, bool hasConverter)
{
// don't read properties with converters as a specific value
// the value might be a string which will then get converted which will error if read as date for example
+4 -4
View File
@@ -54,7 +54,7 @@ namespace Newtonsoft.Json
/// Gets the path to the JSON where the error occurred.
/// </summary>
/// <value>The path to the JSON where the error occurred.</value>
public string Path { get; }
public string? Path { get; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonReaderException"/> class.
@@ -107,7 +107,7 @@ namespace Newtonsoft.Json
/// <param name="lineNumber">The line number indicating where the error occurred.</param>
/// <param name="linePosition">The line position indicating where the error occurred.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or <c>null</c> if no inner exception is specified.</param>
public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception innerException)
public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
: base(message, innerException)
{
Path = path;
@@ -120,12 +120,12 @@ namespace Newtonsoft.Json
return Create(reader, message, null);
}
internal static JsonReaderException Create(JsonReader reader, string message, Exception ex)
internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex)
{
return Create(reader as IJsonLineInfo, reader.Path, message, ex);
}
internal static JsonReaderException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex)
internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
{
message = JsonPosition.FormatMessage(lineInfo, path, message);
@@ -54,7 +54,7 @@ namespace Newtonsoft.Json
/// Gets the path to the JSON where the error occurred.
/// </summary>
/// <value>The path to the JSON where the error occurred.</value>
public string Path { get; }
public string? Path { get; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializationException"/> class.
@@ -107,7 +107,7 @@ namespace Newtonsoft.Json
/// <param name="lineNumber">The line number indicating where the error occurred.</param>
/// <param name="linePosition">The line position indicating where the error occurred.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or <c>null</c> if no inner exception is specified.</param>
public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception innerException)
public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
: base(message, innerException)
{
Path = path;
@@ -120,12 +120,12 @@ namespace Newtonsoft.Json
return Create(reader, message, null);
}
internal static JsonSerializationException Create(JsonReader reader, string message, Exception ex)
internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex)
{
return Create(reader as IJsonLineInfo, reader.Path, message, ex);
}
internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex)
internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
{
message = JsonPosition.FormatMessage(lineInfo, path, message);
+42 -42
View File
@@ -35,6 +35,8 @@ using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
namespace Newtonsoft.Json
{
@@ -54,13 +56,13 @@ namespace Newtonsoft.Json
internal DefaultValueHandling _defaultValueHandling;
internal ConstructorHandling _constructorHandling;
internal MetadataPropertyHandling _metadataPropertyHandling;
internal JsonConverterCollection _converters;
internal JsonConverterCollection? _converters;
internal IContractResolver _contractResolver;
internal ITraceWriter _traceWriter;
internal IEqualityComparer _equalityComparer;
internal ITraceWriter? _traceWriter;
internal IEqualityComparer? _equalityComparer;
internal ISerializationBinder _serializationBinder;
internal StreamingContext _context;
private IReferenceResolver _referenceResolver;
private IReferenceResolver? _referenceResolver;
private Formatting? _formatting;
private DateFormatHandling? _dateFormatHandling;
@@ -73,7 +75,7 @@ namespace Newtonsoft.Json
private int? _maxDepth;
private bool _maxDepthSet;
private bool? _checkAdditionalContent;
private string _dateFormatString;
private string? _dateFormatString;
private bool _dateFormatStringSet;
/// <summary>
@@ -84,7 +86,7 @@ namespace Newtonsoft.Json
/// <summary>
/// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
/// </summary>
public virtual IReferenceResolver ReferenceResolver
public virtual IReferenceResolver? ReferenceResolver
{
get => GetReferenceResolver();
set
@@ -106,11 +108,6 @@ namespace Newtonsoft.Json
{
get
{
if (_serializationBinder == null)
{
return null;
}
if (_serializationBinder is SerializationBinder legacySerializationBinder)
{
return legacySerializationBinder;
@@ -155,7 +152,7 @@ namespace Newtonsoft.Json
/// Gets or sets the <see cref="ITraceWriter"/> used by the serializer when writing trace messages.
/// </summary>
/// <value>The trace writer.</value>
public virtual ITraceWriter TraceWriter
public virtual ITraceWriter? TraceWriter
{
get => _traceWriter;
set => _traceWriter = value;
@@ -165,7 +162,7 @@ namespace Newtonsoft.Json
/// Gets or sets the equality comparer used by the serializer when comparing references.
/// </summary>
/// <value>The equality comparer.</value>
public virtual IEqualityComparer EqualityComparer
public virtual IEqualityComparer? EqualityComparer
{
get => _equalityComparer;
set => _equalityComparer = value;
@@ -599,7 +596,7 @@ namespace Newtonsoft.Json
/// The <see cref="JsonSerializer"/> will not use default settings
/// from <see cref="JsonConvert.DefaultSettings"/>.
/// </returns>
public static JsonSerializer Create(JsonSerializerSettings settings)
public static JsonSerializer Create(JsonSerializerSettings? settings)
{
JsonSerializer serializer = Create();
@@ -624,7 +621,7 @@ namespace Newtonsoft.Json
public static JsonSerializer CreateDefault()
{
// copy static to local variable to avoid concurrency issues
JsonSerializerSettings defaultSettings = JsonConvert.DefaultSettings?.Invoke();
JsonSerializerSettings? defaultSettings = JsonConvert.DefaultSettings?.Invoke();
return Create(defaultSettings);
}
@@ -640,7 +637,7 @@ namespace Newtonsoft.Json
/// The <see cref="JsonSerializer"/> will use default settings
/// from <see cref="JsonConvert.DefaultSettings"/> as well as the specified <see cref="JsonSerializerSettings"/>.
/// </returns>
public static JsonSerializer CreateDefault(JsonSerializerSettings settings)
public static JsonSerializer CreateDefault(JsonSerializerSettings? settings)
{
JsonSerializer serializer = CreateDefault();
if (settings != null)
@@ -814,14 +811,14 @@ namespace Newtonsoft.Json
SetupReader(
reader,
out CultureInfo previousCulture,
out CultureInfo? previousCulture,
out DateTimeZoneHandling? previousDateTimeZoneHandling,
out DateParseHandling? previousDateParseHandling,
out FloatParseHandling? previousFloatParseHandling,
out int? previousMaxDepth,
out string previousDateFormatString);
out string? previousDateFormatString);
TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceJsonReader? traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
? CreateTraceJsonReader(reader)
: null;
@@ -830,7 +827,7 @@ namespace Newtonsoft.Json
if (traceJsonReader != null)
{
TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
TraceWriter!.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
}
ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
@@ -842,7 +839,7 @@ namespace Newtonsoft.Json
/// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to deserialize.</param>
/// <returns>The <see cref="Object"/> being deserialized.</returns>
[DebuggerStepThrough]
public object Deserialize(JsonReader reader)
public object? Deserialize(JsonReader reader)
{
return Deserialize(reader, null);
}
@@ -855,7 +852,7 @@ namespace Newtonsoft.Json
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
[DebuggerStepThrough]
public object Deserialize(TextReader reader, Type objectType)
public object? Deserialize(TextReader reader, Type objectType)
{
return Deserialize(new JsonTextReader(reader), objectType);
}
@@ -868,9 +865,12 @@ namespace Newtonsoft.Json
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns>
[DebuggerStepThrough]
[return: MaybeNull]
public T Deserialize<T>(JsonReader reader)
{
#pragma warning disable CS8601 // Possible null reference assignment.
return (T)Deserialize(reader, typeof(T));
#pragma warning restore CS8601 // Possible null reference assignment.
}
/// <summary>
@@ -881,34 +881,34 @@ namespace Newtonsoft.Json
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
[DebuggerStepThrough]
public object Deserialize(JsonReader reader, Type objectType)
public object? Deserialize(JsonReader reader, Type? objectType)
{
return DeserializeInternal(reader, objectType);
}
internal virtual object DeserializeInternal(JsonReader reader, Type objectType)
internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
SetupReader(
reader,
out CultureInfo previousCulture,
out CultureInfo? previousCulture,
out DateTimeZoneHandling? previousDateTimeZoneHandling,
out DateParseHandling? previousDateParseHandling,
out FloatParseHandling? previousFloatParseHandling,
out int? previousMaxDepth,
out string previousDateFormatString);
out string? previousDateFormatString);
TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceJsonReader? traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
? CreateTraceJsonReader(reader)
: null;
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
object value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent);
object? value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent);
if (traceJsonReader != null)
{
TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
TraceWriter!.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
}
ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
@@ -916,7 +916,7 @@ namespace Newtonsoft.Json
return value;
}
private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString)
private void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString)
{
if (_culture != null && !_culture.Equals(reader.Culture))
{
@@ -987,7 +987,7 @@ namespace Newtonsoft.Json
}
}
private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string previousDateFormatString)
private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString)
{
// reset reader back to previous options
if (previousCulture != null)
@@ -1028,7 +1028,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="textWriter">The <see cref="TextWriter"/> used to write the JSON structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(TextWriter textWriter, object value)
public void Serialize(TextWriter textWriter, object? value)
{
Serialize(new JsonTextWriter(textWriter), value);
}
@@ -1044,7 +1044,7 @@ namespace Newtonsoft.Json
/// This parameter is used when <see cref="JsonSerializer.TypeNameHandling"/> is <see cref="Json.TypeNameHandling.Auto"/> to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType)
{
SerializeInternal(jsonWriter, value, objectType);
}
@@ -1060,7 +1060,7 @@ namespace Newtonsoft.Json
/// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match.
/// Specifying the type is optional.
/// </param>
public void Serialize(TextWriter textWriter, object value, Type objectType)
public void Serialize(TextWriter textWriter, object? value, Type objectType)
{
Serialize(new JsonTextWriter(textWriter), value, objectType);
}
@@ -1071,7 +1071,7 @@ namespace Newtonsoft.Json
/// </summary>
/// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the JSON structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(JsonWriter jsonWriter, object value)
public void Serialize(JsonWriter jsonWriter, object? value)
{
SerializeInternal(jsonWriter, value, null);
}
@@ -1087,7 +1087,7 @@ namespace Newtonsoft.Json
return traceReader;
}
internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType)
internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType)
{
ValidationUtils.ArgumentNotNull(jsonWriter, nameof(jsonWriter));
@@ -1127,21 +1127,21 @@ namespace Newtonsoft.Json
jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault();
}
CultureInfo previousCulture = null;
CultureInfo? previousCulture = null;
if (_culture != null && !_culture.Equals(jsonWriter.Culture))
{
previousCulture = jsonWriter.Culture;
jsonWriter.Culture = _culture;
}
string previousDateFormatString = null;
string? previousDateFormatString = null;
if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString)
{
previousDateFormatString = jsonWriter.DateFormatString;
jsonWriter.DateFormatString = _dateFormatString;
}
TraceJsonWriter traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceJsonWriter? traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
? new TraceJsonWriter(jsonWriter)
: null;
@@ -1150,7 +1150,7 @@ namespace Newtonsoft.Json
if (traceJsonWriter != null)
{
TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null);
TraceWriter!.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null);
}
// reset writer back to previous options
@@ -1194,12 +1194,12 @@ namespace Newtonsoft.Json
return _referenceResolver;
}
internal JsonConverter GetMatchingConverter(Type type)
internal JsonConverter? GetMatchingConverter(Type type)
{
return GetMatchingConverter(_converters, type);
}
internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType)
internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType)
{
#if DEBUG
ValidationUtils.ArgumentNotNull(objectType, nameof(objectType));
+11 -11
View File
@@ -69,11 +69,11 @@ namespace Newtonsoft.Json
internal FloatFormatHandling? _floatFormatHandling;
internal FloatParseHandling? _floatParseHandling;
internal StringEscapeHandling? _stringEscapeHandling;
internal CultureInfo _culture;
internal CultureInfo? _culture;
internal bool? _checkAdditionalContent;
internal int? _maxDepth;
internal bool _maxDepthSet;
internal string _dateFormatString;
internal string? _dateFormatString;
internal bool _dateFormatStringSet;
internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling;
internal DefaultValueHandling? _defaultValueHandling;
@@ -225,27 +225,27 @@ namespace Newtonsoft.Json
/// serializing .NET objects to JSON and vice versa.
/// </summary>
/// <value>The contract resolver.</value>
public IContractResolver ContractResolver { get; set; }
public IContractResolver? ContractResolver { get; set; }
/// <summary>
/// Gets or sets the equality comparer used by the serializer when comparing references.
/// </summary>
/// <value>The equality comparer.</value>
public IEqualityComparer EqualityComparer { get; set; }
public IEqualityComparer? EqualityComparer { get; set; }
/// <summary>
/// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
/// </summary>
/// <value>The reference resolver.</value>
[Obsolete("ReferenceResolver property is obsolete. Use the ReferenceResolverProvider property to set the IReferenceResolver: settings.ReferenceResolverProvider = () => resolver")]
public IReferenceResolver ReferenceResolver
public IReferenceResolver? ReferenceResolver
{
get => ReferenceResolverProvider?.Invoke();
set
{
ReferenceResolverProvider = (value != null)
? () => value
: (Func<IReferenceResolver>)null;
: (Func<IReferenceResolver?>?)null;
}
}
@@ -253,20 +253,20 @@ namespace Newtonsoft.Json
/// Gets or sets a function that creates the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
/// </summary>
/// <value>A function that creates the <see cref="IReferenceResolver"/> used by the serializer when resolving references.</value>
public Func<IReferenceResolver> ReferenceResolverProvider { get; set; }
public Func<IReferenceResolver?>? ReferenceResolverProvider { get; set; }
/// <summary>
/// Gets or sets the <see cref="ITraceWriter"/> used by the serializer when writing trace messages.
/// </summary>
/// <value>The trace writer.</value>
public ITraceWriter TraceWriter { get; set; }
public ITraceWriter? TraceWriter { get; set; }
/// <summary>
/// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names.
/// </summary>
/// <value>The binder.</value>
[Obsolete("Binder is obsolete. Use SerializationBinder instead.")]
public SerializationBinder Binder
public SerializationBinder? Binder
{
get
{
@@ -289,13 +289,13 @@ namespace Newtonsoft.Json
/// Gets or sets the <see cref="ISerializationBinder"/> used by the serializer when resolving type names.
/// </summary>
/// <value>The binder.</value>
public ISerializationBinder SerializationBinder { get; set; }
public ISerializationBinder? SerializationBinder { get; set; }
/// <summary>
/// Gets or sets the error handler called during serialization and deserialization.
/// </summary>
/// <value>The error handler called during serialization and deserialization.</value>
public EventHandler<ErrorEventArgs> Error { get; set; }
public EventHandler<ErrorEventArgs>? Error { get; set; }
/// <summary>
/// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods.
+47 -9
View File
@@ -34,6 +34,7 @@ using System.Numerics;
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using System.Diagnostics;
namespace Newtonsoft.Json
{
@@ -110,6 +111,8 @@ namespace Newtonsoft.Json
private async Task<bool> ParsePostValueAsync(bool ignoreComments, CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
while (true)
{
char currentChar = _chars[_charPos];
@@ -193,6 +196,8 @@ namespace Newtonsoft.Json
private async Task<bool> ReadFromFinishedAsync(CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
@@ -222,6 +227,8 @@ namespace Newtonsoft.Json
private async Task<int> ReadDataAsync(bool append, int charsRequired, CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
if (_isEndOfFile)
{
return 0;
@@ -244,6 +251,8 @@ namespace Newtonsoft.Json
private async Task<bool> ParseValueAsync(CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
while (true)
{
char currentChar = _chars[_charPos];
@@ -373,6 +382,8 @@ namespace Newtonsoft.Json
private async Task ReadStringIntoBufferAsync(char quote, CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
int charPos = _charPos;
int initialPosition = _charPos;
int lastWritePosition = _charPos;
@@ -589,6 +600,8 @@ namespace Newtonsoft.Json
private async Task<bool> ParseObjectAsync(CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
while (true)
{
char currentChar = _chars[_charPos];
@@ -646,6 +659,8 @@ namespace Newtonsoft.Json
private async Task ParseCommentAsync(bool setToken, CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
// should have already parsed / character before reaching this method
_charPos++;
@@ -742,6 +757,8 @@ namespace Newtonsoft.Json
private async Task EatWhitespaceAsync(CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
while (true)
{
char currentChar = _chars[_charPos];
@@ -798,6 +815,8 @@ namespace Newtonsoft.Json
private async Task<bool> MatchValueWithTrailingSeparatorAsync(string value, CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
// will match value and then move to the next character, checking that it is a separator character
if (!await MatchValueAsync(value, cancellationToken).ConfigureAwait(false))
{
@@ -812,7 +831,7 @@ namespace Newtonsoft.Json
return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0';
}
private async Task MatchAndSetAsync(string value, JsonToken newToken, object tokenValue, CancellationToken cancellationToken)
private async Task MatchAndSetAsync(string value, JsonToken newToken, object? tokenValue, CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync(value, cancellationToken).ConfigureAwait(false))
{
@@ -841,6 +860,8 @@ namespace Newtonsoft.Json
private async Task ParseConstructorAsync(CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
if (await MatchValueWithTrailingSeparatorAsync("new", cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
@@ -939,6 +960,8 @@ namespace Newtonsoft.Json
private async Task ParseNumberAsync(ReadType readType, CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
@@ -956,6 +979,8 @@ namespace Newtonsoft.Json
private async Task<bool> ParsePropertyAsync(CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
char firstChar = _chars[_charPos];
char quoteChar;
@@ -1008,6 +1033,8 @@ namespace Newtonsoft.Json
private async Task ReadNumberIntoBufferAsync(CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
int charPos = _charPos;
while (true)
@@ -1042,6 +1069,8 @@ namespace Newtonsoft.Json
private async Task ParseUnquotedPropertyAsync(CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
int initialPosition = _charPos;
// parse unquoted property name until whitespace or colon
@@ -1091,6 +1120,8 @@ namespace Newtonsoft.Json
private async Task HandleNullAsync(CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos + 1] == 'u')
@@ -1109,6 +1140,8 @@ namespace Newtonsoft.Json
private async Task ReadFinishedAsync(CancellationToken cancellationToken)
{
Debug.Assert(_chars != null);
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
@@ -1131,9 +1164,10 @@ namespace Newtonsoft.Json
SetToken(JsonToken.None);
}
private async Task<object> ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken)
private async Task<object?> ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
Debug.Assert(_chars != null);
switch (_currentState)
{
@@ -1266,9 +1300,10 @@ namespace Newtonsoft.Json
}
}
private async Task<object> ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken)
private async Task<object?> ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
Debug.Assert(_chars != null);
switch (_currentState)
{
@@ -1395,6 +1430,7 @@ namespace Newtonsoft.Json
internal async Task<bool?> DoReadAsBooleanAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
Debug.Assert(_chars != null);
switch (_currentState)
{
@@ -1522,14 +1558,16 @@ namespace Newtonsoft.Json
/// property returns the <see cref="byte"/>[]. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<byte[]> ReadAsBytesAsync(CancellationToken cancellationToken = default)
public override Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default)
{
return _safeAsync ? DoReadAsBytesAsync(cancellationToken) : base.ReadAsBytesAsync(cancellationToken);
}
internal async Task<byte[]> DoReadAsBytesAsync(CancellationToken cancellationToken)
internal async Task<byte[]?> DoReadAsBytesAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
Debug.Assert(_chars != null);
bool isWrapped = false;
switch (_currentState)
@@ -1563,7 +1601,7 @@ namespace Newtonsoft.Json
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.ReadAsBytes, cancellationToken).ConfigureAwait(false);
byte[] data = (byte[])Value;
byte[]? data = (byte[]?)Value;
if (isWrapped)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
@@ -1753,14 +1791,14 @@ namespace Newtonsoft.Json
/// property returns the <see cref="string"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<string> ReadAsStringAsync(CancellationToken cancellationToken = default)
public override Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default)
{
return _safeAsync ? DoReadAsStringAsync(cancellationToken) : base.ReadAsStringAsync(cancellationToken);
}
internal async Task<string> DoReadAsStringAsync(CancellationToken cancellationToken)
internal async Task<string?> DoReadAsStringAsync(CancellationToken cancellationToken)
{
return (string)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
return (string?)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
}
}
}
+74 -19
View File
@@ -27,6 +27,7 @@ using System;
using System.Runtime.CompilerServices;
using System.IO;
using System.Globalization;
using System.Diagnostics;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
@@ -66,7 +67,7 @@ namespace Newtonsoft.Json
#endif
private readonly TextReader _reader;
private char[] _chars;
private char[]? _chars;
private int _charsUsed;
private int _charPos;
private int _lineStartPos;
@@ -74,7 +75,7 @@ namespace Newtonsoft.Json
private bool _isEndOfFile;
private StringBuffer _stringBuffer;
private StringReference _stringReference;
private IArrayPool<char> _arrayPool;
private IArrayPool<char>? _arrayPool;
/// <summary>
/// Initializes a new instance of the <see cref="JsonTextReader"/> class with the specified <see cref="TextReader"/>.
@@ -96,7 +97,7 @@ namespace Newtonsoft.Json
}
#if DEBUG
internal char[] CharBuffer
internal char[]? CharBuffer
{
get => _chars;
set => _chars = value;
@@ -108,12 +109,12 @@ namespace Newtonsoft.Json
/// <summary>
/// Gets or sets the reader's property name table.
/// </summary>
public JsonNameTable PropertyNameTable { get; set; }
public JsonNameTable? PropertyNameTable { get; set; }
/// <summary>
/// Gets or sets the reader's character buffer pool.
/// </summary>
public IArrayPool<char> ArrayPool
public IArrayPool<char>? ArrayPool
{
get => _arrayPool;
set
@@ -137,6 +138,8 @@ namespace Newtonsoft.Json
private void SetNewLine(bool hasNextChar)
{
Debug.Assert(_chars != null);
if (hasNextChar && _chars[_charPos] == StringUtils.LineFeed)
{
_charPos++;
@@ -249,6 +252,8 @@ namespace Newtonsoft.Json
private void ShiftBufferIfNeeded()
{
Debug.Assert(_chars != null);
// once in the last 10% of the buffer, or buffer is already very large then
// shift the remaining content to the start to avoid unnecessarily increasing
// the buffer size when reading numbers/strings
@@ -275,6 +280,8 @@ namespace Newtonsoft.Json
private void PrepareBufferForReadData(bool append, int charsRequired)
{
Debug.Assert(_chars != null);
// char buffer is full
if (_charsUsed + charsRequired >= _chars.Length - 1)
{
@@ -338,6 +345,7 @@ namespace Newtonsoft.Json
}
PrepareBufferForReadData(append, charsRequired);
Debug.Assert(_chars != null);
int attemptCharReadCount = _chars.Length - _charsUsed - 1;
@@ -406,6 +414,7 @@ namespace Newtonsoft.Json
public override bool Read()
{
EnsureBuffer();
Debug.Assert(_chars != null);
while (true)
{
@@ -476,18 +485,20 @@ namespace Newtonsoft.Json
/// Reads the next JSON token from the underlying <see cref="TextReader"/> as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public override string ReadAsString()
public override string? ReadAsString()
{
return (string)ReadStringValue(ReadType.ReadAsString);
return (string?)ReadStringValue(ReadType.ReadAsString);
}
/// <summary>
/// Reads the next JSON token from the underlying <see cref="TextReader"/> as a <see cref="Byte"/>[].
/// </summary>
/// <returns>A <see cref="Byte"/>[] or <c>null</c> if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns>
public override byte[] ReadAsBytes()
public override byte[]? ReadAsBytes()
{
EnsureBuffer();
Debug.Assert(_chars != null);
bool isWrapped = false;
switch (_currentState)
@@ -520,7 +531,7 @@ namespace Newtonsoft.Json
case '"':
case '\'':
ParseString(currentChar, ReadType.ReadAsBytes);
byte[] data = (byte[])Value;
byte[]? data = (byte[]?)Value;
if (isWrapped)
{
ReaderReadAndAssert();
@@ -589,9 +600,10 @@ namespace Newtonsoft.Json
}
}
private object ReadStringValue(ReadType readType)
private object? ReadStringValue(ReadType readType)
{
EnsureBuffer();
Debug.Assert(_chars != null);
switch (_currentState)
{
@@ -718,7 +730,7 @@ namespace Newtonsoft.Json
}
}
private object FinishReadQuotedStringValue(ReadType readType)
private object? FinishReadQuotedStringValue(ReadType readType)
{
switch (readType)
{
@@ -731,7 +743,7 @@ namespace Newtonsoft.Json
return time;
}
return ReadDateTimeString((string)Value);
return ReadDateTimeString((string?)Value);
#if HAVE_DATE_TIME_OFFSET
case ReadType.ReadAsDateTimeOffset:
if (Value is DateTimeOffset offset)
@@ -739,7 +751,7 @@ namespace Newtonsoft.Json
return offset;
}
return ReadDateTimeOffsetString((string)Value);
return ReadDateTimeOffsetString((string?)Value);
#endif
default:
throw new ArgumentOutOfRangeException(nameof(readType));
@@ -758,6 +770,7 @@ namespace Newtonsoft.Json
public override bool? ReadAsBoolean()
{
EnsureBuffer();
Debug.Assert(_chars != null);
switch (_currentState)
{
@@ -892,9 +905,10 @@ namespace Newtonsoft.Json
SetStateBasedOnCurrent();
}
private object ReadNumberValue(ReadType readType)
private object? ReadNumberValue(ReadType readType)
{
EnsureBuffer();
Debug.Assert(_chars != null);
switch (_currentState)
{
@@ -1002,7 +1016,7 @@ namespace Newtonsoft.Json
}
}
private object FinishReadQuotedNumber(ReadType readType)
private object? FinishReadQuotedNumber(ReadType readType)
{
switch (readType)
{
@@ -1048,6 +1062,8 @@ namespace Newtonsoft.Json
private void HandleNull()
{
Debug.Assert(_chars != null);
if (EnsureChars(1, true))
{
char next = _chars[_charPos + 1];
@@ -1068,6 +1084,8 @@ namespace Newtonsoft.Json
private void ReadFinished()
{
Debug.Assert(_chars != null);
if (EnsureChars(0, false))
{
EatWhitespace();
@@ -1117,6 +1135,8 @@ namespace Newtonsoft.Json
private void ReadStringIntoBuffer(char quote)
{
Debug.Assert(_chars != null);
int charPos = _charPos;
int initialPosition = _charPos;
int lastWritePosition = _charPos;
@@ -1270,6 +1290,8 @@ namespace Newtonsoft.Json
private void FinishReadStringIntoBuffer(int charPos, int initialPosition, int lastWritePosition)
{
Debug.Assert(_chars != null);
if (initialPosition == lastWritePosition)
{
_stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition);
@@ -1283,7 +1305,7 @@ namespace Newtonsoft.Json
_stringBuffer.Append(_arrayPool, _chars, lastWritePosition, charPos - lastWritePosition);
}
_stringReference = new StringReference(_stringBuffer.InternalBuffer, 0, _stringBuffer.Position);
_stringReference = new StringReference(_stringBuffer.InternalBuffer!, 0, _stringBuffer.Position);
}
_charPos = charPos + 1;
@@ -1291,6 +1313,8 @@ namespace Newtonsoft.Json
private void WriteCharToBuffer(char writeChar, int lastWritePosition, int writeToPosition)
{
Debug.Assert(_chars != null);
if (writeToPosition > lastWritePosition)
{
_stringBuffer.Append(_arrayPool, _chars, lastWritePosition, writeToPosition - lastWritePosition);
@@ -1301,6 +1325,8 @@ namespace Newtonsoft.Json
private char ConvertUnicode(bool enoughChars)
{
Debug.Assert(_chars != null);
if (enoughChars)
{
if (ConvertUtils.TryHexTextToInt(_chars, _charPos, _charPos + 4, out int value))
@@ -1327,6 +1353,8 @@ namespace Newtonsoft.Json
private void ReadNumberIntoBuffer()
{
Debug.Assert(_chars != null);
int charPos = _charPos;
while (true)
@@ -1411,6 +1439,8 @@ namespace Newtonsoft.Json
private bool ParsePostValue(bool ignoreComments)
{
Debug.Assert(_chars != null);
while (true)
{
char currentChar = _chars[_charPos];
@@ -1491,6 +1521,8 @@ namespace Newtonsoft.Json
private bool ParseObject()
{
Debug.Assert(_chars != null);
while (true)
{
char currentChar = _chars[_charPos];
@@ -1545,6 +1577,8 @@ namespace Newtonsoft.Json
private bool ParseProperty()
{
Debug.Assert(_chars != null);
char firstChar = _chars[_charPos];
char quoteChar;
@@ -1566,7 +1600,7 @@ namespace Newtonsoft.Json
throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
string propertyName;
string? propertyName;
if (PropertyNameTable != null)
{
@@ -1606,6 +1640,8 @@ namespace Newtonsoft.Json
private void ParseUnquotedProperty()
{
Debug.Assert(_chars != null);
int initialPosition = _charPos;
// parse unquoted property name until whitespace or colon
@@ -1637,6 +1673,8 @@ namespace Newtonsoft.Json
private bool ReadUnquotedPropertyReportIfDone(char currentChar, int initialPosition)
{
Debug.Assert(_chars != null);
if (ValidIdentifierChar(currentChar))
{
_charPos++;
@@ -1654,6 +1692,8 @@ namespace Newtonsoft.Json
private bool ParseValue()
{
Debug.Assert(_chars != null);
while (true)
{
char currentChar = _chars[_charPos];
@@ -1794,6 +1834,8 @@ namespace Newtonsoft.Json
private void EatWhitespace()
{
Debug.Assert(_chars != null);
while (true)
{
char currentChar = _chars[_charPos];
@@ -1835,6 +1877,8 @@ namespace Newtonsoft.Json
private void ParseConstructor()
{
Debug.Assert(_chars != null);
if (MatchValueWithTrailingSeparator("new"))
{
EatWhitespace();
@@ -1919,6 +1963,7 @@ namespace Newtonsoft.Json
private void ParseNumber(ReadType readType)
{
ShiftBufferIfNeeded();
Debug.Assert(_chars != null);
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
@@ -1929,7 +1974,9 @@ namespace Newtonsoft.Json
}
private void ParseReadNumber(ReadType readType, char firstChar, int initialPosition)
{
{
Debug.Assert(_chars != null);
// set state to PostValue now so that if there is an error parsing the number then the reader can continue
SetPostValueState(true);
@@ -2190,7 +2237,7 @@ namespace Newtonsoft.Json
SetToken(numberType, numberValue, false);
}
private JsonReaderException ThrowReaderError(string message, Exception ex = null)
private JsonReaderException ThrowReaderError(string message, Exception? ex = null)
{
SetToken(JsonToken.Undefined, null, false);
return JsonReaderException.Create(this, message, ex);
@@ -2210,6 +2257,8 @@ namespace Newtonsoft.Json
private void ParseComment(bool setToken)
{
Debug.Assert(_chars != null);
// should have already parsed / character before reaching this method
_charPos++;
@@ -2315,6 +2364,8 @@ namespace Newtonsoft.Json
private bool MatchValue(bool enoughChars, string value)
{
Debug.Assert(_chars != null);
if (!enoughChars)
{
_charPos = _charsUsed;
@@ -2337,6 +2388,8 @@ namespace Newtonsoft.Json
private bool MatchValueWithTrailingSeparator(string value)
{
Debug.Assert(_chars != null);
// will match value and then move to the next character, checking that it is a separator character
bool match = MatchValue(value);
@@ -2355,6 +2408,8 @@ namespace Newtonsoft.Json
private bool IsSeparator(char c)
{
Debug.Assert(_chars != null);
switch (c)
{
case '}':
+23 -19
View File
@@ -33,6 +33,7 @@ using System.Numerics;
#endif
using System.Threading.Tasks;
using Newtonsoft.Json.Utilities;
using System.Diagnostics;
namespace Newtonsoft.Json
{
@@ -164,6 +165,7 @@ namespace Newtonsoft.Json
int currentIndentCount = Top * _indentation;
int newLineLen = SetIndentChars();
Debug.Assert(_indentChars != null);
if (currentIndentCount <= IndentCharBufferSize)
{
@@ -175,6 +177,8 @@ namespace Newtonsoft.Json
private async Task WriteIndentAsync(int currentIndentCount, int newLineLen, CancellationToken cancellationToken)
{
Debug.Assert(_indentChars != null);
await _writer.WriteAsync(_indentChars, 0, newLineLen + Math.Min(currentIndentCount, IndentCharBufferSize), cancellationToken).ConfigureAwait(false);
while ((currentIndentCount -= IndentCharBufferSize) > 0)
@@ -225,12 +229,12 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task WriteRawAsync(string json, CancellationToken cancellationToken = default)
public override Task WriteRawAsync(string? json, CancellationToken cancellationToken = default)
{
return _safeAsync ? DoWriteRawAsync(json, cancellationToken) : base.WriteRawAsync(json, cancellationToken);
}
internal Task DoWriteRawAsync(string json, CancellationToken cancellationToken)
internal Task DoWriteRawAsync(string? json, CancellationToken cancellationToken)
{
return _writer.WriteAsync(json, cancellationToken);
}
@@ -260,7 +264,7 @@ namespace Newtonsoft.Json
}
int length = WriteNumberToBuffer(uvalue, negative);
return _writer.WriteAsync(_writeBuffer, 0, length, cancellationToken);
return _writer.WriteAsync(_writeBuffer!, 0, length, cancellationToken);
}
private Task WriteIntegerValueAsync(ulong uvalue, bool negative, CancellationToken cancellationToken)
@@ -298,7 +302,7 @@ namespace Newtonsoft.Json
private Task WriteEscapedStringAsync(string value, bool quote, CancellationToken cancellationToken)
{
return JavaScriptUtils.WriteEscapedJavaScriptStringAsync(_writer, value, _quoteChar, quote, _charEscapeFlags, StringEscapeHandling, this, _writeBuffer, cancellationToken);
return JavaScriptUtils.WriteEscapedJavaScriptStringAsync(_writer, value, _quoteChar, quote, _charEscapeFlags!, StringEscapeHandling, this, _writeBuffer!, cancellationToken);
}
/// <summary>
@@ -585,7 +589,7 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task WriteValueAsync(byte[] value, CancellationToken cancellationToken = default)
public override Task WriteValueAsync(byte[]? value, CancellationToken cancellationToken = default)
{
return _safeAsync ? (value == null ? WriteNullAsync(cancellationToken) : WriteValueNonNullAsync(value, cancellationToken)) : base.WriteValueAsync(value, cancellationToken);
}
@@ -657,7 +661,7 @@ namespace Newtonsoft.Json
{
int length = WriteValueToBuffer(value);
await _writer.WriteAsync(_writeBuffer, 0, length, cancellationToken).ConfigureAwait(false);
await _writer.WriteAsync(_writeBuffer!, 0, length, cancellationToken).ConfigureAwait(false);
}
else
{
@@ -706,7 +710,7 @@ namespace Newtonsoft.Json
{
int length = WriteValueToBuffer(value);
await _writer.WriteAsync(_writeBuffer, 0, length, cancellationToken).ConfigureAwait(false);
await _writer.WriteAsync(_writeBuffer!, 0, length, cancellationToken).ConfigureAwait(false);
}
else
{
@@ -953,7 +957,7 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task WriteValueAsync(object value, CancellationToken cancellationToken = default)
public override Task WriteValueAsync(object? value, CancellationToken cancellationToken = default)
{
if (_safeAsync)
{
@@ -1046,12 +1050,12 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task WriteValueAsync(string value, CancellationToken cancellationToken = default)
public override Task WriteValueAsync(string? value, CancellationToken cancellationToken = default)
{
return _safeAsync ? DoWriteValueAsync(value, cancellationToken) : base.WriteValueAsync(value, cancellationToken);
}
internal Task DoWriteValueAsync(string value, CancellationToken cancellationToken)
internal Task DoWriteValueAsync(string? value, CancellationToken cancellationToken)
{
Task task = InternalWriteValueAsync(JsonToken.String, cancellationToken);
if (task.IsCompletedSucessfully())
@@ -1062,7 +1066,7 @@ namespace Newtonsoft.Json
return DoWriteValueAsync(task, value, cancellationToken);
}
private async Task DoWriteValueAsync(Task task, string value, CancellationToken cancellationToken)
private async Task DoWriteValueAsync(Task task, string? value, CancellationToken cancellationToken)
{
await task.ConfigureAwait(false);
await (value == null ? _writer.WriteAsync(JsonConvert.Null, cancellationToken) : WriteEscapedStringAsync(value, true, cancellationToken)).ConfigureAwait(false);
@@ -1181,7 +1185,7 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task WriteValueAsync(Uri value, CancellationToken cancellationToken = default)
public override Task WriteValueAsync(Uri? value, CancellationToken cancellationToken = default)
{
return _safeAsync ? (value == null ? WriteNullAsync(cancellationToken) : WriteValueNotNullAsync(value, cancellationToken)) : base.WriteValueAsync(value, cancellationToken);
}
@@ -1244,16 +1248,16 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task WriteCommentAsync(string text, CancellationToken cancellationToken = default)
public override Task WriteCommentAsync(string? text, CancellationToken cancellationToken = default)
{
return _safeAsync ? DoWriteCommentAsync(text, cancellationToken) : base.WriteCommentAsync(text, cancellationToken);
}
internal async Task DoWriteCommentAsync(string text, CancellationToken cancellationToken)
internal async Task DoWriteCommentAsync(string? text, CancellationToken cancellationToken)
{
await InternalWriteCommentAsync(cancellationToken).ConfigureAwait(false);
await _writer.WriteAsync("/*", cancellationToken).ConfigureAwait(false);
await _writer.WriteAsync(text, cancellationToken).ConfigureAwait(false);
await _writer.WriteAsync(text ?? string.Empty, cancellationToken).ConfigureAwait(false);
await _writer.WriteAsync("*/", cancellationToken).ConfigureAwait(false);
}
@@ -1301,12 +1305,12 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task WriteRawValueAsync(string json, CancellationToken cancellationToken = default)
public override Task WriteRawValueAsync(string? json, CancellationToken cancellationToken = default)
{
return _safeAsync ? DoWriteRawValueAsync(json, cancellationToken) : base.WriteRawValueAsync(json, cancellationToken);
}
internal Task DoWriteRawValueAsync(string json, CancellationToken cancellationToken)
internal Task DoWriteRawValueAsync(string? json, CancellationToken cancellationToken)
{
UpdateScopeWithFinishedValue();
Task task = AutoCompleteAsync(JsonToken.Undefined, cancellationToken);
@@ -1318,7 +1322,7 @@ namespace Newtonsoft.Json
return DoWriteRawValueAsync(task, json, cancellationToken);
}
private async Task DoWriteRawValueAsync(Task task, string json, CancellationToken cancellationToken)
private async Task DoWriteRawValueAsync(Task task, string? json, CancellationToken cancellationToken)
{
await task.ConfigureAwait(false);
await WriteRawAsync(json, cancellationToken).ConfigureAwait(false);
@@ -1331,7 +1335,7 @@ namespace Newtonsoft.Json
length = 35;
}
char[] buffer = _writeBuffer;
char[]? buffer = _writeBuffer;
if (buffer == null)
{
return _writeBuffer = BufferUtils.RentBuffer(_arrayPool, length);
+20 -15
View File
@@ -33,6 +33,7 @@ using System.Text;
using System.IO;
using System.Xml;
using Newtonsoft.Json.Utilities;
using System.Diagnostics;
namespace Newtonsoft.Json
{
@@ -43,15 +44,15 @@ namespace Newtonsoft.Json
{
private const int IndentCharBufferSize = 12;
private readonly TextWriter _writer;
private Base64Encoder _base64Encoder;
private Base64Encoder? _base64Encoder;
private char _indentChar;
private int _indentation;
private char _quoteChar;
private bool _quoteName;
private bool[] _charEscapeFlags;
private char[] _writeBuffer;
private IArrayPool<char> _arrayPool;
private char[] _indentChars;
private bool[]? _charEscapeFlags;
private char[]? _writeBuffer;
private IArrayPool<char>? _arrayPool;
private char[]? _indentChars;
private Base64Encoder Base64Encoder
{
@@ -69,7 +70,7 @@ namespace Newtonsoft.Json
/// <summary>
/// Gets or sets the writer's character array pool.
/// </summary>
public IArrayPool<char> ArrayPool
public IArrayPool<char>? ArrayPool
{
get => _arrayPool;
set
@@ -342,7 +343,7 @@ namespace Newtonsoft.Json
{
for (int i = 0; i != newLineLen; ++i)
{
if (writerNewLine[i] != _indentChars[i])
if (writerNewLine[i] != _indentChars![i])
{
match = false;
break;
@@ -387,7 +388,7 @@ namespace Newtonsoft.Json
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public override void WriteValue(object value)
public override void WriteValue(object? value)
{
#if HAVE_BIG_INTEGER
if (value is BigInteger i)
@@ -424,7 +425,7 @@ namespace Newtonsoft.Json
/// Writes raw JSON.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public override void WriteRaw(string json)
public override void WriteRaw(string? json)
{
InternalWriteRaw();
@@ -435,7 +436,7 @@ namespace Newtonsoft.Json
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public override void WriteValue(string value)
public override void WriteValue(string? value)
{
InternalWriteValue(JsonToken.String);
@@ -452,7 +453,7 @@ namespace Newtonsoft.Json
private void WriteEscapedString(string value, bool quote)
{
EnsureWriteBuffer();
JavaScriptUtils.WriteEscapedJavaScriptString(_writer, value, _quoteChar, quote, _charEscapeFlags, StringEscapeHandling, _arrayPool, ref _writeBuffer);
JavaScriptUtils.WriteEscapedJavaScriptString(_writer, value, _quoteChar, quote, _charEscapeFlags!, StringEscapeHandling, _arrayPool, ref _writeBuffer);
}
/// <summary>
@@ -649,6 +650,7 @@ namespace Newtonsoft.Json
private int WriteValueToBuffer(DateTime value)
{
EnsureWriteBuffer();
Debug.Assert(_writeBuffer != null);
int pos = 0;
_writeBuffer[pos++] = _quoteChar;
@@ -661,7 +663,7 @@ namespace Newtonsoft.Json
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public override void WriteValue(byte[] value)
public override void WriteValue(byte[]? value)
{
if (value == null)
{
@@ -703,6 +705,7 @@ namespace Newtonsoft.Json
private int WriteValueToBuffer(DateTimeOffset value)
{
EnsureWriteBuffer();
Debug.Assert(_writeBuffer != null);
int pos = 0;
_writeBuffer[pos++] = _quoteChar;
@@ -720,7 +723,7 @@ namespace Newtonsoft.Json
{
InternalWriteValue(JsonToken.String);
string text = null;
string text;
#if HAVE_CHAR_TO_STRING_WITH_CULTURE
text = value.ToString("D", CultureInfo.InvariantCulture);
@@ -757,7 +760,7 @@ namespace Newtonsoft.Json
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public override void WriteValue(Uri value)
public override void WriteValue(Uri? value)
{
if (value == null)
{
@@ -775,7 +778,7 @@ namespace Newtonsoft.Json
/// Writes a comment <c>/*...*/</c> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public override void WriteComment(string text)
public override void WriteComment(string? text)
{
InternalWriteComment();
@@ -839,6 +842,7 @@ namespace Newtonsoft.Json
}
EnsureWriteBuffer();
Debug.Assert(_writeBuffer != null);
int totalLength = MathUtils.IntLength(value);
@@ -890,6 +894,7 @@ namespace Newtonsoft.Json
private int WriteNumberToBuffer(uint value, bool negative)
{
EnsureWriteBuffer();
Debug.Assert(_writeBuffer != null);
int totalLength = MathUtils.IntLength(value);
@@ -41,6 +41,8 @@ using System.Linq;
#endif
#nullable disable
namespace Newtonsoft.Json
{
/// <summary>
+12 -12
View File
@@ -225,7 +225,7 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task WriteRawAsync(string json, CancellationToken cancellationToken = default)
public virtual Task WriteRawAsync(string? json, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
@@ -546,7 +546,7 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task WriteCommentAsync(string text, CancellationToken cancellationToken = default)
public virtual Task WriteCommentAsync(string? text, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
@@ -570,7 +570,7 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task WriteRawValueAsync(string json, CancellationToken cancellationToken = default)
public virtual Task WriteRawValueAsync(string? json, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
@@ -673,7 +673,7 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public Task WriteTokenAsync(JsonToken token, object value, CancellationToken cancellationToken = default)
public Task WriteTokenAsync(JsonToken token, object? value, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
@@ -755,7 +755,7 @@ namespace Newtonsoft.Json
return WriteValueAsync(guid, cancellationToken);
}
return WriteValueAsync((byte[])value, cancellationToken);
return WriteValueAsync((byte[]?)value, cancellationToken);
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(token), token, "Unexpected token type.");
}
@@ -768,7 +768,7 @@ namespace Newtonsoft.Json
do
{
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal))
{
await WriteConstructorDateAsync(reader, cancellationToken).ConfigureAwait(false);
}
@@ -801,7 +801,7 @@ namespace Newtonsoft.Json
do
{
// write a JValue date when the constructor is for a date
if (reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
if (reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal))
{
WriteConstructorDate(reader);
}
@@ -831,7 +831,7 @@ namespace Newtonsoft.Json
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null);
}
DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime((long)reader.Value);
DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime((long)reader.Value!);
if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
@@ -929,7 +929,7 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task WriteValueAsync(byte[] value, CancellationToken cancellationToken = default)
public virtual Task WriteValueAsync(byte[]? value, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
@@ -1290,7 +1290,7 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task WriteValueAsync(object value, CancellationToken cancellationToken = default)
public virtual Task WriteValueAsync(object? value, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
@@ -1387,7 +1387,7 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task WriteValueAsync(string value, CancellationToken cancellationToken = default)
public virtual Task WriteValueAsync(string? value, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
@@ -1524,7 +1524,7 @@ namespace Newtonsoft.Json
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task WriteValueAsync(Uri value, CancellationToken cancellationToken = default)
public virtual Task WriteValueAsync(Uri? value, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
+17 -17
View File
@@ -116,7 +116,7 @@ namespace Newtonsoft.Json
StateArray = BuildStateArray();
}
private List<JsonPosition> _stack;
private List<JsonPosition>? _stack;
private JsonPosition _currentPosition;
private State _currentState;
private Formatting _formatting;
@@ -218,7 +218,7 @@ namespace Newtonsoft.Json
JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null;
return JsonPosition.BuildPath(_stack, current);
return JsonPosition.BuildPath(_stack!, current);
}
}
@@ -226,8 +226,8 @@ namespace Newtonsoft.Json
private DateTimeZoneHandling _dateTimeZoneHandling;
private StringEscapeHandling _stringEscapeHandling;
private FloatFormatHandling _floatFormatHandling;
private string _dateFormatString;
private CultureInfo _culture;
private string? _dateFormatString;
private CultureInfo? _culture;
/// <summary>
/// Gets or sets a value indicating how JSON text output should be formatted.
@@ -325,7 +325,7 @@ namespace Newtonsoft.Json
/// <summary>
/// Gets or sets how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatted when writing JSON text.
/// </summary>
public string DateFormatString
public string? DateFormatString
{
get => _dateFormatString;
set => _dateFormatString = value;
@@ -522,7 +522,7 @@ namespace Newtonsoft.Json
/// A value is only required for tokens that have an associated value, e.g. the <see cref="String"/> property name for <see cref="JsonToken.PropertyName"/>.
/// <c>null</c> can be passed to the method for tokens that don't have a value, e.g. <see cref="JsonToken.StartObject"/>.
/// </param>
public void WriteToken(JsonToken token, object value)
public void WriteToken(JsonToken token, object? value)
{
switch (token)
{
@@ -625,7 +625,7 @@ namespace Newtonsoft.Json
}
else
{
WriteValue((byte[])value);
WriteValue((byte[])value!);
}
break;
default:
@@ -649,7 +649,7 @@ namespace Newtonsoft.Json
do
{
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal))
{
WriteConstructorDate(reader);
}
@@ -696,7 +696,7 @@ namespace Newtonsoft.Json
private void WriteConstructorDate(JsonReader reader)
{
if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime dateTime, out string errorMessage))
if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime dateTime, out string? errorMessage))
{
throw JsonWriterException.Create(this, errorMessage, null);
}
@@ -787,7 +787,7 @@ namespace Newtonsoft.Json
{
int currentLevel = top - i;
if (_stack[currentLevel].Type == type)
if (_stack![currentLevel].Type == type)
{
levelsToComplete = i + 2;
break;
@@ -909,7 +909,7 @@ namespace Newtonsoft.Json
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
public virtual void WriteRaw(string? json)
{
InternalWriteRaw();
}
@@ -918,7 +918,7 @@ namespace Newtonsoft.Json
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
public virtual void WriteRawValue(string? json)
{
// hack. want writer to change state as if a value had been written
UpdateScopeWithFinishedValue();
@@ -930,7 +930,7 @@ namespace Newtonsoft.Json
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string value)
public virtual void WriteValue(string? value)
{
InternalWriteValue(JsonToken.String);
}
@@ -1376,7 +1376,7 @@ namespace Newtonsoft.Json
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public virtual void WriteValue(byte[] value)
public virtual void WriteValue(byte[]? value)
{
if (value == null)
{
@@ -1392,7 +1392,7 @@ namespace Newtonsoft.Json
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri value)
public virtual void WriteValue(Uri? value)
{
if (value == null)
{
@@ -1409,7 +1409,7 @@ namespace Newtonsoft.Json
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object value)
public virtual void WriteValue(object? value)
{
if (value == null)
{
@@ -1435,7 +1435,7 @@ namespace Newtonsoft.Json
/// Writes a comment <c>/*...*/</c> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string text)
public virtual void WriteComment(string? text)
{
InternalWriteComment();
}
+4 -4
View File
@@ -42,7 +42,7 @@ namespace Newtonsoft.Json
/// Gets the path to the JSON where the error occurred.
/// </summary>
/// <value>The path to the JSON where the error occurred.</value>
public string Path { get; }
public string? Path { get; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonWriterException"/> class.
@@ -93,18 +93,18 @@ namespace Newtonsoft.Json
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="path">The path to the JSON where the error occurred.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or <c>null</c> if no inner exception is specified.</param>
public JsonWriterException(string message, string path, Exception innerException)
public JsonWriterException(string message, string path, Exception? innerException)
: base(message, innerException)
{
Path = path;
}
internal static JsonWriterException Create(JsonWriter writer, string message, Exception ex)
internal static JsonWriterException Create(JsonWriter writer, string message, Exception? ex)
{
return Create(writer.ContainerPath, message, ex);
}
internal static JsonWriterException Create(string path, string message, Exception ex)
internal static JsonWriterException Create(string path, string message, Exception? ex)
{
message = JsonPosition.FormatMessage(null, path, message);
+12 -5
View File
@@ -27,6 +27,8 @@ using System;
using System.Collections.Generic;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
@@ -111,7 +113,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
/// <param name="key">The token key.</param>
/// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every token in the source collection with the given key.</returns>
public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source, object key)
public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source, object? key)
{
return Values<JToken, JToken>(source, key).AsJEnumerable();
}
@@ -179,7 +181,7 @@ namespace Newtonsoft.Json.Linq
return token.Convert<JToken, U>();
}
internal static IEnumerable<U> Values<T, U>(this IEnumerable<T> source, object key) where T : JToken
internal static IEnumerable<U> Values<T, U>(this IEnumerable<T> source, object? key) where T : JToken
{
ValidationUtils.ArgumentNotNull(source, nameof(source));
@@ -204,7 +206,7 @@ namespace Newtonsoft.Json.Linq
{
foreach (T token in source)
{
JToken value = token[key];
JToken? value = token[key];
if (value != null)
{
yield return value.Convert<JToken, U>();
@@ -251,11 +253,14 @@ namespace Newtonsoft.Json.Linq
}
}
internal static U Convert<T, U>(this T token) where T : JToken
[return: MaybeNull]
internal static U Convert<T, U>(this T token) where T : JToken?
{
if (token == null)
{
#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter.
return default;
#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter.
}
if (token is U castValue
@@ -282,7 +287,9 @@ namespace Newtonsoft.Json.Linq
{
if (value.Value == null)
{
#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter.
return default;
#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter.
}
targetType = Nullable.GetUnderlyingType(targetType);
@@ -315,7 +322,7 @@ namespace Newtonsoft.Json.Linq
{
if (source == null)
{
return null;
return null!;
}
else if (source is IJEnumerable<T> customEnumerable)
{
+1 -1
View File
@@ -73,7 +73,7 @@ namespace Newtonsoft.Json.Linq
/// If this is <c>null</c>, default load settings will be used.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the asynchronous load. The <see cref="Task{TResult}.Result"/> property contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public new static async Task<JArray> LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default)
public new static async Task<JArray> LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default)
{
if (reader.TokenType == JsonToken.None)
{
+11 -6
View File
@@ -115,7 +115,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON.
/// If this is <c>null</c>, default load settings will be used.</param>
/// <returns>A <see cref="JArray"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public new static JArray Load(JsonReader reader, JsonLoadSettings settings)
public new static JArray Load(JsonReader reader, JsonLoadSettings? settings)
{
if (reader.TokenType == JsonToken.None)
{
@@ -163,7 +163,7 @@ namespace Newtonsoft.Json.Linq
/// <example>
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParseArray" title="Parsing a JSON Array from Text" />
/// </example>
public new static JArray Parse(string json, JsonLoadSettings settings)
public new static JArray Parse(string json, JsonLoadSettings? settings)
{
using (JsonReader reader = new JsonTextReader(new StringReader(json)))
{
@@ -227,7 +227,7 @@ namespace Newtonsoft.Json.Linq
/// Gets the <see cref="JToken"/> with the specified key.
/// </summary>
/// <value>The <see cref="JToken"/> with the specified key.</value>
public override JToken this[object key]
public override JToken? this[object key]
{
get
{
@@ -263,14 +263,19 @@ namespace Newtonsoft.Json.Linq
set => SetItem(index, value);
}
internal override int IndexOfItem(JToken item)
internal override int IndexOfItem(JToken? item)
{
if (item == null)
{
return -1;
}
return _values.IndexOfReference(item);
}
internal override void MergeItem(object content, JsonMergeSettings settings)
internal override void MergeItem(object content, JsonMergeSettings? settings)
{
IEnumerable a = (IsMultiContent(content) || content is JArray)
IEnumerable? a = (IsMultiContent(content) || content is JArray)
? (IEnumerable)content
: null;
if (a == null)
@@ -43,7 +43,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters)
{
await writer.WriteStartConstructorAsync(_name, cancellationToken).ConfigureAwait(false);
await writer.WriteStartConstructorAsync(_name ?? string.Empty, cancellationToken).ConfigureAwait(false);
for (int i = 0; i < _values.Count; i++)
{
@@ -76,7 +76,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>
/// A <see cref="Task{TResult}"/> that represents the asynchronous load. The <see cref="Task{TResult}.Result"/>
/// property returns a <see cref="JConstructor"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public new static async Task<JConstructor> LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default)
public new static async Task<JConstructor> LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default)
{
if (reader.TokenType == JsonToken.None)
{
@@ -93,7 +93,7 @@ namespace Newtonsoft.Json.Linq
throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
JConstructor c = new JConstructor((string)reader.Value);
JConstructor c = new JConstructor((string)reader.Value!);
c.SetLineInfo(reader as IJsonLineInfo, settings);
await c.ReadTokenFromAsync(reader, settings, cancellationToken).ConfigureAwait(false);
+14 -9
View File
@@ -36,7 +36,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
public partial class JConstructor : JContainer
{
private string _name;
private string? _name;
private readonly List<JToken> _values = new List<JToken>();
/// <summary>
@@ -45,12 +45,17 @@ namespace Newtonsoft.Json.Linq
/// <value>The container's children tokens.</value>
protected override IList<JToken> ChildrenTokens => _values;
internal override int IndexOfItem(JToken item)
internal override int IndexOfItem(JToken? item)
{
if (item == null)
{
return -1;
}
return _values.IndexOfReference(item);
}
internal override void MergeItem(object content, JsonMergeSettings settings)
internal override void MergeItem(object content, JsonMergeSettings? settings)
{
if (!(content is JConstructor c))
{
@@ -68,7 +73,7 @@ namespace Newtonsoft.Json.Linq
/// Gets or sets the name of this constructor.
/// </summary>
/// <value>The constructor name.</value>
public string Name
public string? Name
{
get => _name;
set => _name = value;
@@ -154,7 +159,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{
writer.WriteStartConstructor(_name);
writer.WriteStartConstructor(_name!);
int count = _values.Count;
for (int i = 0; i < count; i++)
@@ -169,7 +174,7 @@ namespace Newtonsoft.Json.Linq
/// Gets the <see cref="JToken"/> with the specified key.
/// </summary>
/// <value>The <see cref="JToken"/> with the specified key.</value>
public override JToken this[object key]
public override JToken? this[object key]
{
get
{
@@ -197,7 +202,7 @@ namespace Newtonsoft.Json.Linq
internal override int GetDeepHashCode()
{
return _name.GetHashCode() ^ ContentsHashCode();
return (_name?.GetHashCode() ?? 0) ^ ContentsHashCode();
}
/// <summary>
@@ -217,7 +222,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON.
/// If this is <c>null</c>, default load settings will be used.</param>
/// <returns>A <see cref="JConstructor"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public new static JConstructor Load(JsonReader reader, JsonLoadSettings settings)
public new static JConstructor Load(JsonReader reader, JsonLoadSettings? settings)
{
if (reader.TokenType == JsonToken.None)
{
@@ -234,7 +239,7 @@ namespace Newtonsoft.Json.Linq
throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
JConstructor c = new JConstructor((string)reader.Value);
JConstructor c = new JConstructor((string)reader.Value!);
c.SetLineInfo(reader as IJsonLineInfo, settings);
c.ReadTokenFrom(reader, settings);
+10 -7
View File
@@ -26,6 +26,7 @@
#if HAVE_ASYNC
using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
@@ -35,7 +36,7 @@ namespace Newtonsoft.Json.Linq
{
public abstract partial class JContainer
{
internal async Task ReadTokenFromAsync(JsonReader reader, JsonLoadSettings options, CancellationToken cancellationToken = default)
internal async Task ReadTokenFromAsync(JsonReader reader, JsonLoadSettings? options, CancellationToken cancellationToken = default)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
int startDepth = reader.Depth;
@@ -53,11 +54,11 @@ namespace Newtonsoft.Json.Linq
}
}
private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default)
private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default)
{
IJsonLineInfo lineInfo = reader as IJsonLineInfo;
IJsonLineInfo? lineInfo = reader as IJsonLineInfo;
JContainer parent = this;
JContainer? parent = this;
do
{
@@ -71,6 +72,8 @@ namespace Newtonsoft.Json.Linq
parent = parent.Parent;
}
Debug.Assert(parent != null);
switch (reader.TokenType)
{
case JsonToken.None:
@@ -106,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;
@@ -132,7 +135,7 @@ namespace Newtonsoft.Json.Linq
case JsonToken.Comment:
if (settings != null && settings.CommentHandling == CommentHandling.Load)
{
v = JValue.CreateComment(reader.Value.ToString());
v = JValue.CreateComment(reader.Value!.ToString());
v.SetLineInfo(lineInfo, settings);
parent.Add(v);
}
@@ -148,7 +151,7 @@ namespace Newtonsoft.Json.Linq
parent.Add(v);
break;
case JsonToken.PropertyName:
JProperty property = ReadProperty(reader, settings, lineInfo, parent);
JProperty? property = ReadProperty(reader, settings, lineInfo, parent);
if (property != null)
{
parent = property;
+62 -55
View File
@@ -33,11 +33,13 @@ using Newtonsoft.Json.Utilities;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Linq
@@ -55,8 +57,8 @@ namespace Newtonsoft.Json.Linq
#endif
{
#if HAVE_COMPONENT_MODEL
internal ListChangedEventHandler _listChanged;
internal AddingNewEventHandler _addingNew;
internal ListChangedEventHandler? _listChanged;
internal AddingNewEventHandler? _addingNew;
/// <summary>
/// Occurs when the list changes or an item in the list changes.
@@ -77,7 +79,7 @@ namespace Newtonsoft.Json.Linq
}
#endif
#if HAVE_INOTIFY_COLLECTION_CHANGED
internal NotifyCollectionChangedEventHandler _collectionChanged;
internal NotifyCollectionChangedEventHandler? _collectionChanged;
/// <summary>
/// Occurs when the items list of the collection has changed, or the collection is reset.
@@ -95,7 +97,7 @@ namespace Newtonsoft.Json.Linq
/// <value>The container's children tokens.</value>
protected abstract IList<JToken> ChildrenTokens { get; }
private object _syncRoot;
private object? _syncRoot;
#if (HAVE_COMPONENT_MODEL || HAVE_INOTIFY_COLLECTION_CHANGED)
private bool _busy;
#endif
@@ -148,7 +150,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="e">The <see cref="ListChangedEventArgs"/> instance containing the event data.</param>
protected virtual void OnListChanged(ListChangedEventArgs e)
{
ListChangedEventHandler handler = _listChanged;
ListChangedEventHandler? handler = _listChanged;
if (handler != null)
{
@@ -171,7 +173,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
NotifyCollectionChangedEventHandler handler = _collectionChanged;
NotifyCollectionChangedEventHandler? handler = _collectionChanged;
if (handler != null)
{
@@ -228,7 +230,7 @@ namespace Newtonsoft.Json.Linq
/// <value>
/// A <see cref="JToken"/> containing the first child token of the <see cref="JToken"/>.
/// </value>
public override JToken First
public override JToken? First
{
get
{
@@ -243,7 +245,7 @@ namespace Newtonsoft.Json.Linq
/// <value>
/// A <see cref="JToken"/> containing the last child token of the <see cref="JToken"/>.
/// </value>
public override JToken Last
public override JToken? Last
{
get
{
@@ -314,12 +316,12 @@ namespace Newtonsoft.Json.Linq
}
}
internal bool IsMultiContent(object content)
internal bool IsMultiContent([NotNull]object? content)
{
return (content is IEnumerable && !(content is string) && !(content is JToken) && !(content is byte[]));
}
internal JToken EnsureParentToken(JToken item, bool skipParentCheck)
internal JToken EnsureParentToken(JToken? item, bool skipParentCheck)
{
if (item == null)
{
@@ -343,9 +345,9 @@ namespace Newtonsoft.Json.Linq
return item;
}
internal abstract int IndexOfItem(JToken item);
internal abstract int IndexOfItem(JToken? item);
internal virtual void InsertItem(int index, JToken item, bool skipParentCheck)
internal virtual void InsertItem(int index, JToken? item, bool skipParentCheck)
{
IList<JToken> children = ChildrenTokens;
@@ -358,9 +360,9 @@ namespace Newtonsoft.Json.Linq
item = EnsureParentToken(item, skipParentCheck);
JToken previous = (index == 0) ? null : children[index - 1];
JToken? previous = (index == 0) ? null : children[index - 1];
// haven't inserted new token yet so next token is still at the inserting index
JToken next = (index == children.Count) ? null : children[index];
JToken? next = (index == children.Count) ? null : children[index];
ValidateToken(item, null);
@@ -410,8 +412,8 @@ namespace Newtonsoft.Json.Linq
CheckReentrancy();
JToken item = children[index];
JToken previous = (index == 0) ? null : children[index - 1];
JToken next = (index == children.Count - 1) ? null : children[index + 1];
JToken? previous = (index == 0) ? null : children[index - 1];
JToken? next = (index == children.Count - 1) ? null : children[index + 1];
if (previous != null)
{
@@ -442,13 +444,16 @@ namespace Newtonsoft.Json.Linq
#endif
}
internal virtual bool RemoveItem(JToken item)
internal virtual bool RemoveItem(JToken? item)
{
int index = IndexOfItem(item);
if (index >= 0)
if (item != null)
{
RemoveItemAt(index);
return true;
int index = IndexOfItem(item);
if (index >= 0)
{
RemoveItemAt(index);
return true;
}
}
return false;
@@ -459,7 +464,7 @@ namespace Newtonsoft.Json.Linq
return ChildrenTokens[index];
}
internal virtual void SetItem(int index, JToken item)
internal virtual void SetItem(int index, JToken? item)
{
IList<JToken> children = ChildrenTokens;
@@ -485,8 +490,8 @@ namespace Newtonsoft.Json.Linq
ValidateToken(item, existing);
JToken previous = (index == 0) ? null : children[index - 1];
JToken next = (index == children.Count - 1) ? null : children[index + 1];
JToken? previous = (index == 0) ? null : children[index - 1];
JToken? next = (index == children.Count - 1) ? null : children[index + 1];
item.Parent = this;
@@ -562,7 +567,7 @@ namespace Newtonsoft.Json.Linq
SetItem(index, replacement);
}
internal virtual bool ContainsItem(JToken item)
internal virtual bool ContainsItem(JToken? item)
{
return (IndexOfItem(item) != -1);
}
@@ -594,14 +599,14 @@ namespace Newtonsoft.Json.Linq
}
}
internal static bool IsTokenUnchanged(JToken currentValue, JToken newValue)
internal static bool IsTokenUnchanged(JToken currentValue, JToken? newValue)
{
if (currentValue is JValue v1)
{
// null will get turned into a JValue of type null
if (v1.Type == JTokenType.Null && newValue == null)
if (newValue == null)
{
return true;
// null will get turned into a JValue of type null
return v1.Type == JTokenType.Null;
}
return v1.Equals(newValue);
@@ -610,7 +615,7 @@ namespace Newtonsoft.Json.Linq
return false;
}
internal virtual void ValidateToken(JToken o, JToken existing)
internal virtual void ValidateToken(JToken o, JToken? existing)
{
ValidationUtils.ArgumentNotNull(o, nameof(o));
@@ -624,7 +629,7 @@ namespace Newtonsoft.Json.Linq
/// Adds the specified content as children of this <see cref="JToken"/>.
/// </summary>
/// <param name="content">The content to be added.</param>
public virtual void Add(object content)
public virtual void Add(object? content)
{
AddInternal(ChildrenTokens.Count, content, false);
}
@@ -638,12 +643,12 @@ namespace Newtonsoft.Json.Linq
/// Adds the specified content as the first children of this <see cref="JToken"/>.
/// </summary>
/// <param name="content">The content to be added.</param>
public void AddFirst(object content)
public void AddFirst(object? content)
{
AddInternal(0, content, false);
}
internal void AddInternal(int index, object content, bool skipParentCheck)
internal void AddInternal(int index, object? content, bool skipParentCheck)
{
if (IsMultiContent(content))
{
@@ -664,7 +669,7 @@ namespace Newtonsoft.Json.Linq
}
}
internal static JToken CreateFromContent(object content)
internal static JToken CreateFromContent(object? content)
{
if (content is JToken token)
{
@@ -701,7 +706,7 @@ namespace Newtonsoft.Json.Linq
ClearItems();
}
internal abstract void MergeItem(object content, JsonMergeSettings settings);
internal abstract void MergeItem(object content, JsonMergeSettings? settings);
/// <summary>
/// Merge the specified content into this <see cref="JToken"/>.
@@ -709,7 +714,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="content">The content to be merged.</param>
public void Merge(object content)
{
MergeItem(content, new JsonMergeSettings());
MergeItem(content, null);
}
/// <summary>
@@ -717,12 +722,12 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="content">The content to be merged.</param>
/// <param name="settings">The <see cref="JsonMergeSettings"/> used to merge the content.</param>
public void Merge(object content, JsonMergeSettings settings)
public void Merge(object content, JsonMergeSettings? settings)
{
MergeItem(content, settings);
}
internal void ReadTokenFrom(JsonReader reader, JsonLoadSettings options)
internal void ReadTokenFrom(JsonReader reader, JsonLoadSettings? options)
{
int startDepth = reader.Depth;
@@ -741,12 +746,12 @@ namespace Newtonsoft.Json.Linq
}
}
internal void ReadContentFrom(JsonReader r, JsonLoadSettings settings)
internal void ReadContentFrom(JsonReader r, JsonLoadSettings? settings)
{
ValidationUtils.ArgumentNotNull(r, nameof(r));
IJsonLineInfo lineInfo = r as IJsonLineInfo;
IJsonLineInfo? lineInfo = r as IJsonLineInfo;
JContainer parent = this;
JContainer? parent = this;
do
{
@@ -760,6 +765,8 @@ namespace Newtonsoft.Json.Linq
parent = parent.Parent;
}
Debug.Assert(parent != null);
switch (r.TokenType)
{
case JsonToken.None:
@@ -795,7 +802,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;
@@ -821,7 +828,7 @@ namespace Newtonsoft.Json.Linq
case JsonToken.Comment:
if (settings != null && settings.CommentHandling == CommentHandling.Load)
{
v = JValue.CreateComment(r.Value.ToString());
v = JValue.CreateComment(r.Value!.ToString());
v.SetLineInfo(lineInfo, settings);
parent.Add(v);
}
@@ -837,7 +844,7 @@ namespace Newtonsoft.Json.Linq
parent.Add(v);
break;
case JsonToken.PropertyName:
JProperty property = ReadProperty(r, settings, lineInfo, parent);
JProperty? property = ReadProperty(r, settings, lineInfo, parent);
if (property != null)
{
parent = property;
@@ -853,13 +860,13 @@ namespace Newtonsoft.Json.Linq
} while (r.Read());
}
private static JProperty ReadProperty(JsonReader r, JsonLoadSettings settings, IJsonLineInfo lineInfo, JContainer parent)
private static JProperty? ReadProperty(JsonReader r, JsonLoadSettings? settings, IJsonLineInfo? lineInfo, JContainer parent)
{
DuplicatePropertyNameHandling duplicatePropertyNameHandling = settings?.DuplicatePropertyNameHandling ?? DuplicatePropertyNameHandling.Replace;
JObject parentObject = (JObject)parent;
string propertyName = r.Value.ToString();
JProperty existingPropertyWithName = parentObject.Property(propertyName, StringComparison.Ordinal);
string propertyName = r.Value!.ToString();
JProperty? existingPropertyWithName = parentObject.Property(propertyName, StringComparison.Ordinal);
if (existingPropertyWithName != null)
{
if (duplicatePropertyNameHandling == DuplicatePropertyNameHandling.Ignore)
@@ -903,9 +910,9 @@ namespace Newtonsoft.Json.Linq
return string.Empty;
}
PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors)
PropertyDescriptorCollection? ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors)
{
ICustomTypeDescriptor d = First as ICustomTypeDescriptor;
ICustomTypeDescriptor? d = First as ICustomTypeDescriptor;
return d?.GetProperties();
}
#endif
@@ -962,7 +969,7 @@ namespace Newtonsoft.Json.Linq
}
#endregion
private JToken EnsureValue(object value)
private JToken? EnsureValue(object value)
{
if (value == null)
{
@@ -1108,7 +1115,7 @@ namespace Newtonsoft.Json.Linq
ListSortDirection IBindingList.SortDirection => ListSortDirection.Ascending;
PropertyDescriptor IBindingList.SortProperty => null;
PropertyDescriptor? IBindingList.SortProperty => null;
bool IBindingList.SupportsChangeNotification => true;
@@ -1118,9 +1125,9 @@ namespace Newtonsoft.Json.Linq
#endif
#endregion
internal static void MergeEnumerableContent(JContainer target, IEnumerable content, JsonMergeSettings settings)
internal static void MergeEnumerableContent(JContainer target, IEnumerable content, JsonMergeSettings? settings)
{
switch (settings.MergeArrayHandling)
switch (settings?.MergeArrayHandling ?? MergeArrayHandling.Concat)
{
case MergeArrayHandling.Concat:
foreach (JToken item in content)
@@ -1169,7 +1176,7 @@ namespace Newtonsoft.Json.Linq
{
if (i < target.Count)
{
JToken sourceItem = target[i];
JToken? sourceItem = target[i];
if (sourceItem is JContainer existingContainer)
{
+1 -1
View File
@@ -97,7 +97,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>
/// A <see cref="Task{TResult}"/> that represents the asynchronous load. The <see cref="Task{TResult}.Result"/>
/// property returns a <see cref="JObject"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public new static async Task<JObject> LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default)
public new static async Task<JObject> LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
+54 -47
View File
@@ -37,6 +37,8 @@ using System.Linq.Expressions;
using System.IO;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
@@ -51,7 +53,7 @@ namespace Newtonsoft.Json.Linq
/// <example>
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from Text" />
/// </example>
public partial class JObject : JContainer, IDictionary<string, JToken>, INotifyPropertyChanged
public partial class JObject : JContainer, IDictionary<string, JToken?>, INotifyPropertyChanged
#if HAVE_COMPONENT_MODEL
, ICustomTypeDescriptor
#endif
@@ -123,12 +125,17 @@ namespace Newtonsoft.Json.Linq
return _properties.Compare(t._properties);
}
internal override int IndexOfItem(JToken item)
internal override int IndexOfItem(JToken? item)
{
if (item == null)
{
return -1;
}
return _properties.IndexOfReference(item);
}
internal override void InsertItem(int index, JToken item, bool skipParentCheck)
internal override void InsertItem(int index, JToken? item, bool skipParentCheck)
{
// don't add comments to JObject, no name to reference comment by
if (item != null && item.Type == JTokenType.Comment)
@@ -139,7 +146,7 @@ namespace Newtonsoft.Json.Linq
base.InsertItem(index, item, skipParentCheck);
}
internal override void ValidateToken(JToken o, JToken existing)
internal override void ValidateToken(JToken o, JToken? existing)
{
ValidationUtils.ArgumentNotNull(o, nameof(o));
@@ -166,16 +173,16 @@ namespace Newtonsoft.Json.Linq
}
}
internal override void MergeItem(object content, JsonMergeSettings settings)
internal override void MergeItem(object content, JsonMergeSettings? settings)
{
if (!(content is JObject o))
{
return;
}
foreach (KeyValuePair<string, JToken> contentItem in o)
foreach (KeyValuePair<string, JToken?> contentItem in o)
{
JProperty existingProperty = Property(contentItem.Key, settings?.PropertyNameComparison ?? StringComparison.Ordinal);
JProperty? existingProperty = Property(contentItem.Key, settings?.PropertyNameComparison ?? StringComparison.Ordinal);
if (existingProperty == null)
{
@@ -262,7 +269,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="name">The property name.</param>
/// <returns>A <see cref="JProperty"/> with the specified name or <c>null</c>.</returns>
public JProperty Property(string name)
public JProperty? Property(string name)
{
return Property(name, StringComparison.Ordinal);
}
@@ -275,14 +282,14 @@ namespace Newtonsoft.Json.Linq
/// <param name="name">The property name.</param>
/// <param name="comparison">One of the enumeration values that specifies how the strings will be compared.</param>
/// <returns>A <see cref="JProperty"/> matched with the specified name or <c>null</c>.</returns>
public JProperty Property(string name, StringComparison comparison)
public JProperty? Property(string name, StringComparison comparison)
{
if (name == null)
{
return null;
}
if (_properties.TryGetValue(name, out JToken property))
if (_properties.TryGetValue(name, out JToken? property))
{
return (JProperty)property;
}
@@ -316,7 +323,7 @@ namespace Newtonsoft.Json.Linq
/// Gets the <see cref="JToken"/> with the specified key.
/// </summary>
/// <value>The <see cref="JToken"/> with the specified key.</value>
public override JToken this[object key]
public override JToken? this[object key]
{
get
{
@@ -346,29 +353,29 @@ namespace Newtonsoft.Json.Linq
/// Gets or sets the <see cref="JToken"/> with the specified property name.
/// </summary>
/// <value></value>
public JToken this[string propertyName]
public JToken? this[string propertyName]
{
get
{
ValidationUtils.ArgumentNotNull(propertyName, nameof(propertyName));
JProperty property = Property(propertyName, StringComparison.Ordinal);
JProperty? property = Property(propertyName, StringComparison.Ordinal);
return property?.Value;
}
set
{
JProperty property = Property(propertyName, StringComparison.Ordinal);
JProperty? property = Property(propertyName, StringComparison.Ordinal);
if (property != null)
{
property.Value = value;
property.Value = value!;
}
else
{
#if HAVE_INOTIFY_PROPERTY_CHANGING
OnPropertyChanging(propertyName);
#endif
Add(new JProperty(propertyName, value));
Add(propertyName, value);
OnPropertyChanged(propertyName);
}
}
@@ -397,7 +404,7 @@ namespace Newtonsoft.Json.Linq
/// <exception cref="JsonReaderException">
/// <paramref name="reader"/> is not valid JSON.
/// </exception>
public new static JObject Load(JsonReader reader, JsonLoadSettings settings)
public new static JObject Load(JsonReader reader, JsonLoadSettings? settings)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
@@ -453,7 +460,7 @@ namespace Newtonsoft.Json.Linq
/// <example>
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from Text" />
/// </example>
public new static JObject Parse(string json, JsonLoadSettings settings)
public new static JObject Parse(string json, JsonLoadSettings? settings)
{
using (JsonReader reader = new JsonTextReader(new StringReader(json)))
{
@@ -488,7 +495,7 @@ namespace Newtonsoft.Json.Linq
{
JToken token = FromObjectInternal(o, jsonSerializer);
if (token != null && token.Type != JTokenType.Object)
if (token.Type != JTokenType.Object)
{
throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type));
}
@@ -518,7 +525,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns>The <see cref="Newtonsoft.Json.Linq.JToken"/> with the specified property name.</returns>
public JToken GetValue(string propertyName)
public JToken? GetValue(string? propertyName)
{
return GetValue(propertyName, StringComparison.Ordinal);
}
@@ -531,7 +538,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="propertyName">Name of the property.</param>
/// <param name="comparison">One of the enumeration values that specifies how the strings will be compared.</param>
/// <returns>The <see cref="Newtonsoft.Json.Linq.JToken"/> with the specified property name.</returns>
public JToken GetValue(string propertyName, StringComparison comparison)
public JToken? GetValue(string? propertyName, StringComparison comparison)
{
if (propertyName == null)
{
@@ -553,7 +560,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="value">The value.</param>
/// <param name="comparison">One of the enumeration values that specifies how the strings will be compared.</param>
/// <returns><c>true</c> if a value was successfully retrieved; otherwise, <c>false</c>.</returns>
public bool TryGetValue(string propertyName, StringComparison comparison, out JToken value)
public bool TryGetValue(string propertyName, StringComparison comparison, [NotNullWhen(true)]out JToken? value)
{
value = GetValue(propertyName, comparison);
return (value != null);
@@ -565,7 +572,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="value">The value.</param>
public void Add(string propertyName, JToken value)
public void Add(string propertyName, JToken? value)
{
Add(new JProperty(propertyName, value));
}
@@ -582,7 +589,7 @@ namespace Newtonsoft.Json.Linq
return _properties.Contains(propertyName);
}
ICollection<string> IDictionary<string, JToken>.Keys => _properties.Keys;
ICollection<string> IDictionary<string, JToken?>.Keys => _properties.Keys;
/// <summary>
/// Removes the property with the specified name.
@@ -591,7 +598,7 @@ namespace Newtonsoft.Json.Linq
/// <returns><c>true</c> if item was successfully removed; otherwise, <c>false</c>.</returns>
public bool Remove(string propertyName)
{
JProperty property = Property(propertyName, StringComparison.Ordinal);
JProperty? property = Property(propertyName, StringComparison.Ordinal);
if (property == null)
{
return false;
@@ -607,9 +614,9 @@ namespace Newtonsoft.Json.Linq
/// <param name="propertyName">Name of the property.</param>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if a value was successfully retrieved; otherwise, <c>false</c>.</returns>
public bool TryGetValue(string propertyName, out JToken value)
public bool TryGetValue(string propertyName, [NotNullWhen(true)]out JToken? value)
{
JProperty property = Property(propertyName, StringComparison.Ordinal);
JProperty? property = Property(propertyName, StringComparison.Ordinal);
if (property == null)
{
value = null;
@@ -620,24 +627,24 @@ namespace Newtonsoft.Json.Linq
return true;
}
ICollection<JToken> IDictionary<string, JToken>.Values => throw new NotImplementedException();
ICollection<JToken?> IDictionary<string, JToken?>.Values => throw new NotImplementedException();
#endregion
#region ICollection<KeyValuePair<string,JToken>> Members
void ICollection<KeyValuePair<string, JToken>>.Add(KeyValuePair<string, JToken> item)
void ICollection<KeyValuePair<string, JToken?>>.Add(KeyValuePair<string, JToken?> item)
{
Add(new JProperty(item.Key, item.Value));
}
void ICollection<KeyValuePair<string, JToken>>.Clear()
void ICollection<KeyValuePair<string, JToken?>>.Clear()
{
RemoveAll();
}
bool ICollection<KeyValuePair<string, JToken>>.Contains(KeyValuePair<string, JToken> item)
bool ICollection<KeyValuePair<string, JToken?>>.Contains(KeyValuePair<string, JToken?> item)
{
JProperty property = Property(item.Key, StringComparison.Ordinal);
JProperty? property = Property(item.Key, StringComparison.Ordinal);
if (property == null)
{
return false;
@@ -646,7 +653,7 @@ namespace Newtonsoft.Json.Linq
return (property.Value == item.Value);
}
void ICollection<KeyValuePair<string, JToken>>.CopyTo(KeyValuePair<string, JToken>[] array, int arrayIndex)
void ICollection<KeyValuePair<string, JToken?>>.CopyTo(KeyValuePair<string, JToken?>[] array, int arrayIndex)
{
if (array == null)
{
@@ -668,16 +675,16 @@ namespace Newtonsoft.Json.Linq
int index = 0;
foreach (JProperty property in _properties)
{
array[arrayIndex + index] = new KeyValuePair<string, JToken>(property.Name, property.Value);
array[arrayIndex + index] = new KeyValuePair<string, JToken?>(property.Name, property.Value);
index++;
}
}
bool ICollection<KeyValuePair<string, JToken>>.IsReadOnly => false;
bool ICollection<KeyValuePair<string, JToken?>>.IsReadOnly => false;
bool ICollection<KeyValuePair<string, JToken>>.Remove(KeyValuePair<string, JToken> item)
bool ICollection<KeyValuePair<string, JToken?>>.Remove(KeyValuePair<string, JToken?> item)
{
if (!((ICollection<KeyValuePair<string, JToken>>)this).Contains(item))
if (!((ICollection<KeyValuePair<string, JToken?>>)this).Contains(item))
{
return false;
}
@@ -698,11 +705,11 @@ namespace Newtonsoft.Json.Linq
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<KeyValuePair<string, JToken>> GetEnumerator()
public IEnumerator<KeyValuePair<string, JToken?>> GetEnumerator()
{
foreach (JProperty property in _properties)
{
yield return new KeyValuePair<string, JToken>(property.Name, property.Value);
yield return new KeyValuePair<string, JToken?>(property.Name, property.Value);
}
}
@@ -739,7 +746,7 @@ namespace Newtonsoft.Json.Linq
{
PropertyDescriptorCollection descriptors = new PropertyDescriptorCollection(null);
foreach (KeyValuePair<string, JToken> propertyValue in this)
foreach (KeyValuePair<string, JToken?> propertyValue in this)
{
descriptors.Add(new JPropertyDescriptor(propertyValue.Key));
}
@@ -752,12 +759,12 @@ namespace Newtonsoft.Json.Linq
return AttributeCollection.Empty;
}
string ICustomTypeDescriptor.GetClassName()
string? ICustomTypeDescriptor.GetClassName()
{
return null;
}
string ICustomTypeDescriptor.GetComponentName()
string? ICustomTypeDescriptor.GetComponentName()
{
return null;
}
@@ -767,17 +774,17 @@ namespace Newtonsoft.Json.Linq
return new TypeConverter();
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
EventDescriptor? ICustomTypeDescriptor.GetDefaultEvent()
{
return null;
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
PropertyDescriptor? ICustomTypeDescriptor.GetDefaultProperty()
{
return null;
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
object? ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return null;
}
@@ -792,7 +799,7 @@ namespace Newtonsoft.Json.Linq
return EventDescriptorCollection.Empty;
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
object? ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
if (pd is JPropertyDescriptor)
{
@@ -820,7 +827,7 @@ namespace Newtonsoft.Json.Linq
private class JObjectDynamicProxy : DynamicProxy<JObject>
{
public override bool TryGetMember(JObject instance, GetMemberBinder binder, out object result)
public override bool TryGetMember(JObject instance, GetMemberBinder binder, out object? result)
{
// result can be null
result = instance[binder.Name];
+2 -2
View File
@@ -88,7 +88,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the asynchronous creation. The <see cref="Task{TResult}.Result"/>
/// property returns a <see cref="JProperty"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public new static async Task<JProperty> LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default)
public new static async Task<JProperty> LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default)
{
if (reader.TokenType == JsonToken.None)
{
@@ -105,7 +105,7 @@ namespace Newtonsoft.Json.Linq
throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
JProperty p = new JProperty((string)reader.Value);
JProperty p = new JProperty((string)reader.Value!);
p.SetLineInfo(reader as IJsonLineInfo, settings);
await p.ReadTokenFromAsync(reader, settings, cancellationToken).ConfigureAwait(false);
+33 -17
View File
@@ -40,7 +40,7 @@ namespace Newtonsoft.Json.Linq
#region JPropertyList
private class JPropertyList : IList<JToken>
{
internal JToken _token;
internal JToken? _token;
public IEnumerator<JToken> GetEnumerator()
{
@@ -115,13 +115,24 @@ namespace Newtonsoft.Json.Linq
public JToken this[int index]
{
get => (index == 0) ? _token : null;
get
{
if (index != 0)
{
throw new IndexOutOfRangeException();
}
Debug.Assert(_token != null);
return _token;
}
set
{
if (index == 0)
if (index != 0)
{
_token = value;
throw new IndexOutOfRangeException();
}
_token = value;
}
}
}
@@ -153,7 +164,7 @@ namespace Newtonsoft.Json.Linq
public JToken Value
{
[DebuggerStepThrough]
get { return _content._token; }
get { return _content._token!; }
set
{
CheckReentrancy();
@@ -191,7 +202,7 @@ namespace Newtonsoft.Json.Linq
return Value;
}
internal override void SetItem(int index, JToken item)
internal override void SetItem(int index, JToken? item)
{
if (index != 0)
{
@@ -203,14 +214,14 @@ namespace Newtonsoft.Json.Linq
return;
}
((JObject)Parent)?.InternalPropertyChanging(this);
((JObject?)Parent)?.InternalPropertyChanging(this);
base.SetItem(0, item);
((JObject)Parent)?.InternalPropertyChanged(this);
((JObject?)Parent)?.InternalPropertyChanged(this);
}
internal override bool RemoveItem(JToken item)
internal override bool RemoveItem(JToken? item)
{
throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty)));
}
@@ -220,12 +231,17 @@ namespace Newtonsoft.Json.Linq
throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty)));
}
internal override int IndexOfItem(JToken item)
internal override int IndexOfItem(JToken? item)
{
if (item == null)
{
return -1;
}
return _content.IndexOf(item);
}
internal override void InsertItem(int index, JToken item, bool skipParentCheck)
internal override void InsertItem(int index, JToken? item, bool skipParentCheck)
{
// don't add comments to JProperty
if (item != null && item.Type == JTokenType.Comment)
@@ -241,14 +257,14 @@ namespace Newtonsoft.Json.Linq
base.InsertItem(0, item, false);
}
internal override bool ContainsItem(JToken item)
internal override bool ContainsItem(JToken? item)
{
return (Value == item);
}
internal override void MergeItem(object content, JsonMergeSettings settings)
internal override void MergeItem(object content, JsonMergeSettings? settings)
{
JToken value = (content as JProperty)?.Value;
JToken? value = (content as JProperty)?.Value;
if (value != null && value.Type != JTokenType.Null)
{
@@ -304,7 +320,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="name">The property name.</param>
/// <param name="content">The property content.</param>
public JProperty(string name, object content)
public JProperty(string name, object? content)
{
ValidationUtils.ArgumentNotNull(name, nameof(name));
@@ -357,7 +373,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON.
/// If this is <c>null</c>, default load settings will be used.</param>
/// <returns>A <see cref="JProperty"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns>
public new static JProperty Load(JsonReader reader, JsonLoadSettings settings)
public new static JProperty Load(JsonReader reader, JsonLoadSettings? settings)
{
if (reader.TokenType == JsonToken.None)
{
@@ -374,7 +390,7 @@ namespace Newtonsoft.Json.Linq
throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
JProperty p = new JProperty((string)reader.Value);
JProperty p = new JProperty((string)reader.Value!);
p.SetLineInfo(reader as IJsonLineInfo, settings);
p.ReadTokenFrom(reader, settings);
@@ -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];
}
@@ -26,6 +26,8 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Linq
@@ -34,7 +36,7 @@ namespace Newtonsoft.Json.Linq
{
private static readonly IEqualityComparer<string> Comparer = StringComparer.Ordinal;
private Dictionary<string, JToken> _dictionary;
private Dictionary<string, JToken>? _dictionary;
public JPropertyKeyedCollection() : base(new List<JToken>())
{
@@ -43,7 +45,7 @@ namespace Newtonsoft.Json.Linq
private void AddKey(string key, JToken item)
{
EnsureDictionary();
_dictionary[key] = item;
_dictionary![key] = item;
}
protected void ChangeItemKey(JToken item, string newKey)
@@ -189,7 +191,7 @@ namespace Newtonsoft.Json.Linq
}
}
public bool TryGetValue(string key, out JToken value)
public bool TryGetValue(string key, [NotNullWhen(true)]out JToken? value)
{
if (_dictionary == null)
{
@@ -205,7 +207,7 @@ namespace Newtonsoft.Json.Linq
get
{
EnsureDictionary();
return _dictionary.Keys;
return _dictionary!.Keys;
}
}
@@ -214,7 +216,7 @@ namespace Newtonsoft.Json.Linq
get
{
EnsureDictionary();
return _dictionary.Values;
return _dictionary!.Values;
}
}
@@ -232,8 +234,8 @@ namespace Newtonsoft.Json.Linq
// dictionaries in JavaScript aren't ordered
// ignore order when comparing properties
Dictionary<string, JToken> d1 = _dictionary;
Dictionary<string, JToken> d2 = other._dictionary;
Dictionary<string, JToken>? d1 = _dictionary;
Dictionary<string, JToken>? d2 = other._dictionary;
if (d1 == null && d2 == null)
{
@@ -242,7 +244,7 @@ namespace Newtonsoft.Json.Linq
if (d1 == null)
{
return (d2.Count == 0);
return (d2!.Count == 0);
}
if (d2 == null)
+1 -1
View File
@@ -46,7 +46,7 @@ namespace Newtonsoft.Json.Linq
/// Initializes a new instance of the <see cref="JRaw"/> class.
/// </summary>
/// <param name="rawJson">The raw json.</param>
public JRaw(object rawJson)
public JRaw(object? rawJson)
: base(rawJson, JTokenType.Raw)
{
}
+4 -4
View File
@@ -89,7 +89,7 @@ namespace Newtonsoft.Json.Linq
/// that were read from the reader. The runtime type of the token is determined
/// by the token type of the first token encountered in the reader.
/// </returns>
public static async Task<JToken> ReadFromAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default)
public static async Task<JToken> ReadFromAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
@@ -101,7 +101,7 @@ namespace Newtonsoft.Json.Linq
}
}
IJsonLineInfo lineInfo = reader as IJsonLineInfo;
IJsonLineInfo? lineInfo = reader as IJsonLineInfo;
switch (reader.TokenType)
{
@@ -123,7 +123,7 @@ namespace Newtonsoft.Json.Linq
v.SetLineInfo(lineInfo, settings);
return v;
case JsonToken.Comment:
v = JValue.CreateComment(reader.Value.ToString());
v = JValue.CreateComment(reader.Value?.ToString());
v.SetLineInfo(lineInfo, settings);
return v;
case JsonToken.Null:
@@ -168,7 +168,7 @@ namespace Newtonsoft.Json.Linq
/// that were read from the reader. The runtime type of the token is determined
/// by the token type of the first token encountered in the reader.
/// </returns>
public static Task<JToken> LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default)
public static Task<JToken> LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default)
{
return ReadFromAsync(reader, settings, cancellationToken);
}
+99 -88
View File
@@ -38,11 +38,12 @@ using Newtonsoft.Json.Utilities;
using System.Diagnostics;
using System.Globalization;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Linq
@@ -60,10 +61,10 @@ namespace Newtonsoft.Json.Linq
{
private static JTokenEqualityComparer _equalityComparer;
private JContainer _parent;
private JToken _previous;
private JToken _next;
private object _annotations;
private JContainer? _parent;
private JToken? _previous;
private JToken? _next;
private object? _annotations;
private static readonly JTokenType[] BooleanTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean };
private static readonly JTokenType[] NumberTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean };
@@ -99,7 +100,7 @@ namespace Newtonsoft.Json.Linq
/// Gets or sets the parent.
/// </summary>
/// <value>The parent.</value>
public JContainer Parent
public JContainer? Parent
{
[DebuggerStepThrough]
get { return _parent; }
@@ -114,7 +115,7 @@ namespace Newtonsoft.Json.Linq
{
get
{
JContainer parent = Parent;
JContainer? parent = Parent;
if (parent == null)
{
return this;
@@ -161,7 +162,7 @@ namespace Newtonsoft.Json.Linq
/// Gets the next sibling token of this node.
/// </summary>
/// <value>The <see cref="JToken"/> that contains the next sibling token.</value>
public JToken Next
public JToken? Next
{
get => _next;
internal set => _next = value;
@@ -171,7 +172,7 @@ namespace Newtonsoft.Json.Linq
/// Gets the previous sibling token of this node.
/// </summary>
/// <value>The <see cref="JToken"/> that contains the previous sibling token.</value>
public JToken Previous
public JToken? Previous
{
get => _previous;
internal set => _previous = value;
@@ -190,8 +191,8 @@ namespace Newtonsoft.Json.Linq
}
List<JsonPosition> positions = new List<JsonPosition>();
JToken previous = null;
for (JToken current = this; current != null; current = current.Parent)
JToken? previous = null;
for (JToken? current = this; current != null; current = current.Parent)
{
switch (current.Type)
{
@@ -277,7 +278,7 @@ namespace Newtonsoft.Json.Linq
internal IEnumerable<JToken> GetAncestors(bool self)
{
for (JToken current = self ? this : Parent; current != null; current = current.Parent)
for (JToken? current = self ? this : Parent; current != null; current = current.Parent)
{
yield return current;
}
@@ -294,7 +295,7 @@ namespace Newtonsoft.Json.Linq
yield break;
}
for (JToken o = Next; o != null; o = o.Next)
for (JToken? o = Next; o != null; o = o.Next)
{
yield return o;
}
@@ -306,7 +307,12 @@ namespace Newtonsoft.Json.Linq
/// <returns>A collection of the sibling tokens before this token, in document order.</returns>
public IEnumerable<JToken> BeforeSelf()
{
for (JToken o = Parent.First; o != this; o = o.Next)
if (Parent == null)
{
yield break;
}
for (JToken? o = Parent.First; o != this && o != null; o = o.Next)
{
yield return o;
}
@@ -316,7 +322,7 @@ namespace Newtonsoft.Json.Linq
/// Gets the <see cref="JToken"/> with the specified key.
/// </summary>
/// <value>The <see cref="JToken"/> with the specified key.</value>
public virtual JToken this[object key]
public virtual JToken? this[object key]
{
get => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType()));
set => throw new InvalidOperationException("Cannot set child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType()));
@@ -330,7 +336,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The converted token value.</returns>
public virtual T Value<T>(object key)
{
JToken token = this[key];
JToken? token = this[key];
// null check to fix MonoTouch issue - https://github.com/dolbz/Newtonsoft.Json/commit/a24e3062846b30ee505f3271ac08862bb471b822
return token == null ? default : Extensions.Convert<JToken, T>(token);
@@ -340,13 +346,13 @@ namespace Newtonsoft.Json.Linq
/// Get the first child token of this token.
/// </summary>
/// <value>A <see cref="JToken"/> containing the first child token of the <see cref="JToken"/>.</value>
public virtual JToken First => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType()));
public virtual JToken? First => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType()));
/// <summary>
/// Get the last child token of this token.
/// </summary>
/// <value>A <see cref="JToken"/> containing the last child token of the <see cref="JToken"/>.</value>
public virtual JToken Last => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType()));
public virtual JToken? Last => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType()));
/// <summary>
/// Returns a collection of the child tokens of this token, in document order.
@@ -441,7 +447,7 @@ namespace Newtonsoft.Json.Linq
}
}
private static JValue EnsureValue(JToken value)
private static JValue? EnsureValue(JToken value)
{
if (value == null)
{
@@ -453,7 +459,7 @@ namespace Newtonsoft.Json.Linq
value = property.Value;
}
JValue v = value as JValue;
JValue? v = value as JValue;
return v;
}
@@ -483,7 +489,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator bool(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, BooleanTypes, false))
{
throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -507,7 +513,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator DateTimeOffset(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, DateTimeTypes, false))
{
throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -539,7 +545,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, BooleanTypes, true))
{
throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -562,7 +568,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator long(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, false))
{
throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -590,7 +596,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, DateTimeTypes, true))
{
throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -619,7 +625,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, DateTimeTypes, true))
{
throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -655,7 +661,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
{
throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -683,7 +689,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
{
throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -711,7 +717,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, CharTypes, true))
{
throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -734,7 +740,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator int(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, false))
{
throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -757,7 +763,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator short(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, false))
{
throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -781,7 +787,7 @@ namespace Newtonsoft.Json.Linq
[CLSCompliant(false)]
public static explicit operator ushort(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, false))
{
throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -805,7 +811,7 @@ namespace Newtonsoft.Json.Linq
[CLSCompliant(false)]
public static explicit operator char(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, CharTypes, false))
{
throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -828,7 +834,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator byte(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, false))
{
throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -852,7 +858,7 @@ namespace Newtonsoft.Json.Linq
[CLSCompliant(false)]
public static explicit operator sbyte(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, false))
{
throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -880,7 +886,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
{
throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -908,7 +914,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
{
throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -937,7 +943,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
{
throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -965,7 +971,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
{
throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -994,7 +1000,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
{
throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1017,7 +1023,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator DateTime(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, DateTimeTypes, false))
{
throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1045,7 +1051,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
{
throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1073,7 +1079,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
{
throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1096,7 +1102,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator decimal(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, false))
{
throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1125,7 +1131,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
{
throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1154,7 +1160,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, true))
{
throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1177,7 +1183,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator double(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, false))
{
throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1200,7 +1206,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator float(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, false))
{
throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1221,14 +1227,14 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator string(JToken value)
public static explicit operator string?(JToken value)
{
if (value == null)
{
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, StringTypes, true))
{
throw new ArgumentException("Can not convert {0} to String.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1262,7 +1268,7 @@ namespace Newtonsoft.Json.Linq
[CLSCompliant(false)]
public static explicit operator uint(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, false))
{
throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1286,7 +1292,7 @@ namespace Newtonsoft.Json.Linq
[CLSCompliant(false)]
public static explicit operator ulong(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, NumberTypes, false))
{
throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1307,14 +1313,14 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator byte[](JToken value)
public static explicit operator byte[]?(JToken value)
{
if (value == null)
{
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, BytesTypes, false))
{
throw new ArgumentException("Can not convert {0} to byte array.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1346,7 +1352,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator Guid(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, GuidTypes, false))
{
throw new ArgumentException("Can not convert {0} to Guid.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1372,7 +1378,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, GuidTypes, true))
{
throw new ArgumentException("Can not convert {0} to Guid.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1398,7 +1404,7 @@ namespace Newtonsoft.Json.Linq
/// <returns>The result of the conversion.</returns>
public static explicit operator TimeSpan(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, TimeSpanTypes, false))
{
throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1419,7 +1425,7 @@ namespace Newtonsoft.Json.Linq
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, TimeSpanTypes, true))
{
throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1438,14 +1444,14 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator Uri(JToken value)
public static explicit operator Uri?(JToken value)
{
if (value == null)
{
return null;
}
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, UriTypes, true))
{
throw new ArgumentException("Can not convert {0} to Uri.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1462,18 +1468,18 @@ namespace Newtonsoft.Json.Linq
#if HAVE_BIG_INTEGER
private static BigInteger ToBigInteger(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, BigIntegerTypes, false))
{
throw new ArgumentException("Can not convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
return ConvertUtils.ToBigInteger(v.Value);
return ConvertUtils.ToBigInteger(v.Value!);
}
private static BigInteger? ToBigIntegerNullable(JToken value)
{
JValue v = EnsureValue(value);
JValue? v = EnsureValue(value);
if (v == null || !ValidateToken(v, BigIntegerTypes, true))
{
throw new ArgumentException("Can not convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
@@ -1867,7 +1873,7 @@ namespace Newtonsoft.Json.Linq
internal abstract int GetDeepHashCode();
IJEnumerable<JToken> IJEnumerable<JToken>.this[object key] => this[key];
IJEnumerable<JToken> IJEnumerable<JToken>.this[object key] => this[key]!;
/// <summary>
/// Creates a <see cref="JsonReader"/> for this token.
@@ -1887,7 +1893,7 @@ namespace Newtonsoft.Json.Linq
using (JTokenWriter jsonWriter = new JTokenWriter())
{
jsonSerializer.Serialize(jsonWriter, o);
token = jsonWriter.Token;
token = jsonWriter.Token!;
}
return token;
@@ -1919,9 +1925,12 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <typeparam name="T">The object type that the token will be deserialized to.</typeparam>
/// <returns>The new object created from the JSON value.</returns>
[return: MaybeNull]
public T ToObject<T>()
{
#pragma warning disable CS8601 // Possible null reference assignment.
return (T)ToObject(typeof(T));
#pragma warning restore CS8601 // Possible null reference assignment.
}
/// <summary>
@@ -1929,7 +1938,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="objectType">The object type that the token will be deserialized to.</param>
/// <returns>The new object created from the JSON value.</returns>
public object ToObject(Type objectType)
public object? ToObject(Type objectType)
{
if (JsonConvert.DefaultSettings == null)
{
@@ -1947,7 +1956,7 @@ namespace Newtonsoft.Json.Linq
catch (Exception ex)
{
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);
throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string?)this, enumType.Name), ex);
}
}
@@ -2023,13 +2032,13 @@ namespace Newtonsoft.Json.Linq
return (DateTimeOffset)this;
#endif
case PrimitiveTypeCode.String:
return (string)this;
return (string?)this;
case PrimitiveTypeCode.GuidNullable:
return (Guid?)this;
case PrimitiveTypeCode.Guid:
return (Guid)this;
case PrimitiveTypeCode.Uri:
return (Uri)this;
return (Uri?)this;
case PrimitiveTypeCode.TimeSpanNullable:
return (TimeSpan?)this;
case PrimitiveTypeCode.TimeSpan:
@@ -2052,9 +2061,12 @@ namespace Newtonsoft.Json.Linq
/// <typeparam name="T">The object type that the token will be deserialized to.</typeparam>
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used when creating the object.</param>
/// <returns>The new object created from the JSON value.</returns>
[return: MaybeNull]
public T ToObject<T>(JsonSerializer jsonSerializer)
{
#pragma warning disable CS8601 // Possible null reference assignment.
return (T)ToObject(typeof(T), jsonSerializer);
#pragma warning restore CS8601 // Possible null reference assignment.
}
/// <summary>
@@ -2063,7 +2075,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="objectType">The object type that the token will be deserialized to.</param>
/// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used when creating the object.</param>
/// <returns>The new object created from the JSON value.</returns>
public object ToObject(Type objectType, JsonSerializer jsonSerializer)
public object? ToObject(Type objectType, JsonSerializer jsonSerializer)
{
ValidationUtils.ArgumentNotNull(jsonSerializer, nameof(jsonSerializer));
@@ -2098,7 +2110,7 @@ namespace Newtonsoft.Json.Linq
/// that were read from the reader. The runtime type of the token is determined
/// by the token type of the first token encountered in the reader.
/// </returns>
public static JToken ReadFrom(JsonReader reader, JsonLoadSettings settings)
public static JToken ReadFrom(JsonReader reader, JsonLoadSettings? settings)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
@@ -2123,7 +2135,7 @@ namespace Newtonsoft.Json.Linq
throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader.");
}
IJsonLineInfo lineInfo = reader as IJsonLineInfo;
IJsonLineInfo? lineInfo = reader as IJsonLineInfo;
switch (reader.TokenType)
{
@@ -2145,7 +2157,7 @@ namespace Newtonsoft.Json.Linq
v.SetLineInfo(lineInfo, settings);
return v;
case JsonToken.Comment:
v = JValue.CreateComment(reader.Value.ToString());
v = JValue.CreateComment(reader.Value!.ToString());
v.SetLineInfo(lineInfo, settings);
return v;
case JsonToken.Null:
@@ -2178,7 +2190,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON.
/// If this is <c>null</c>, default load settings will be used.</param>
/// <returns>A <see cref="JToken"/> populated from the string that contains JSON.</returns>
public static JToken Parse(string json, JsonLoadSettings settings)
public static JToken Parse(string json, JsonLoadSettings? settings)
{
using (JsonReader reader = new JsonTextReader(new StringReader(json)))
{
@@ -2189,7 +2201,6 @@ namespace Newtonsoft.Json.Linq
// Any content encountered here other than a comment will throw in the reader.
}
return t;
}
}
@@ -2205,7 +2216,7 @@ namespace Newtonsoft.Json.Linq
/// that were read from the reader. The runtime type of the token is determined
/// by the token type of the first token encountered in the reader.
/// </returns>
public static JToken Load(JsonReader reader, JsonLoadSettings settings)
public static JToken Load(JsonReader reader, JsonLoadSettings? settings)
{
return ReadFrom(reader, settings);
}
@@ -2224,7 +2235,7 @@ namespace Newtonsoft.Json.Linq
return Load(reader, null);
}
internal void SetLineInfo(IJsonLineInfo lineInfo, JsonLoadSettings settings)
internal void SetLineInfo(IJsonLineInfo? lineInfo, JsonLoadSettings? settings)
{
if (settings != null && settings.LineInfoHandling != LineInfoHandling.Load)
{
@@ -2265,7 +2276,7 @@ namespace Newtonsoft.Json.Linq
{
get
{
LineInfoAnnotation annotation = Annotation<LineInfoAnnotation>();
LineInfoAnnotation? annotation = Annotation<LineInfoAnnotation>();
if (annotation != null)
{
return annotation.LineNumber;
@@ -2279,7 +2290,7 @@ namespace Newtonsoft.Json.Linq
{
get
{
LineInfoAnnotation annotation = Annotation<LineInfoAnnotation>();
LineInfoAnnotation? annotation = Annotation<LineInfoAnnotation>();
if (annotation != null)
{
return annotation.LinePosition;
@@ -2296,7 +2307,7 @@ namespace Newtonsoft.Json.Linq
/// A <see cref="String"/> that contains a JPath expression.
/// </param>
/// <returns>A <see cref="JToken"/>, or <c>null</c>.</returns>
public JToken SelectToken(string path)
public JToken? SelectToken(string path)
{
return SelectToken(path, false);
}
@@ -2309,11 +2320,11 @@ namespace Newtonsoft.Json.Linq
/// </param>
/// <param name="errorWhenNoMatch">A flag to indicate whether an error should be thrown if no tokens are found when evaluating part of the expression.</param>
/// <returns>A <see cref="JToken"/>.</returns>
public JToken SelectToken(string path, bool errorWhenNoMatch)
public JToken? SelectToken(string path, bool errorWhenNoMatch)
{
JPath p = new JPath(path);
JToken token = null;
JToken? token = null;
foreach (JToken t in p.Evaluate(this, this, errorWhenNoMatch))
{
if (token != null)
@@ -2438,7 +2449,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <typeparam name="T">The type of the annotation to retrieve.</typeparam>
/// <returns>The first annotation object that matches the specified type, or <c>null</c> if no annotation is of the specified type.</returns>
public T Annotation<T>() where T : class
public T? Annotation<T>() where T : class
{
if (_annotations != null)
{
@@ -2469,7 +2480,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="type">The <see cref="Type"/> of the annotation to retrieve.</param>
/// <returns>The first annotation object that matches the specified type, or <c>null</c> if no annotation is of the specified type.</returns>
public object Annotation(Type type)
public object? Annotation(Type type)
{
if (type == null)
{
@@ -2595,7 +2606,7 @@ namespace Newtonsoft.Json.Linq
{
if (_annotations != null)
{
if (!(_annotations is object[] annotations))
if (!(_annotations is object?[] annotations))
{
if (_annotations is T)
{
@@ -2608,7 +2619,7 @@ namespace Newtonsoft.Json.Linq
int keepCount = 0;
while (index < annotations.Length)
{
object obj2 = annotations[index];
object? obj2 = annotations[index];
if (obj2 == null)
{
break;
@@ -2650,7 +2661,7 @@ namespace Newtonsoft.Json.Linq
if (_annotations != null)
{
if (!(_annotations is object[] annotations))
if (!(_annotations is object?[] annotations))
{
if (type.IsInstanceOfType(_annotations))
{
@@ -2663,7 +2674,7 @@ namespace Newtonsoft.Json.Linq
int keepCount = 0;
while (index < annotations.Length)
{
object o = annotations[index];
object? o = annotations[index];
if (o == null)
{
break;
+13 -13
View File
@@ -34,14 +34,14 @@ namespace Newtonsoft.Json.Linq
public class JTokenReader : JsonReader, IJsonLineInfo
{
private readonly JToken _root;
private string _initialPath;
private JToken _parent;
private JToken _current;
private string? _initialPath;
private JToken? _parent;
private JToken? _current;
/// <summary>
/// Gets the <see cref="JToken"/> at the reader's current position.
/// </summary>
public JToken CurrentToken => _current;
public JToken? CurrentToken => _current;
/// <summary>
/// Initializes a new instance of the <see cref="JTokenReader"/> class.
@@ -102,8 +102,8 @@ namespace Newtonsoft.Json.Linq
return ReadToEnd();
}
JToken next = t.Next;
if ((next == null || next == t) || t == t.Parent.Last)
JToken? next = t.Next;
if ((next == null || next == t) || t == t.Parent!.Last)
{
if (t.Parent == null)
{
@@ -146,7 +146,7 @@ namespace Newtonsoft.Json.Linq
private bool ReadInto(JContainer c)
{
JToken firstChild = c.First;
JToken? firstChild = c.First;
if (firstChild == null)
{
return SetEnd(c);
@@ -215,7 +215,7 @@ namespace Newtonsoft.Json.Linq
break;
case JTokenType.Date:
{
object v = ((JValue)token).Value;
object? v = ((JValue)token).Value;
if (v is DateTime dt)
{
v = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
@@ -235,7 +235,7 @@ namespace Newtonsoft.Json.Linq
break;
case JTokenType.Uri:
{
object v = ((JValue)token).Value;
object? v = ((JValue)token).Value;
SetToken(JsonToken.String, v is Uri uri ? uri.OriginalString : SafeToString(v));
break;
}
@@ -247,7 +247,7 @@ namespace Newtonsoft.Json.Linq
}
}
private string SafeToString(object value)
private string? SafeToString(object? value)
{
return value?.ToString();
}
@@ -259,7 +259,7 @@ namespace Newtonsoft.Json.Linq
return false;
}
IJsonLineInfo info = _current;
IJsonLineInfo? info = _current;
return (info != null && info.HasLineInfo());
}
@@ -272,7 +272,7 @@ namespace Newtonsoft.Json.Linq
return 0;
}
IJsonLineInfo info = _current;
IJsonLineInfo? info = _current;
if (info != null)
{
return info.LineNumber;
@@ -291,7 +291,7 @@ namespace Newtonsoft.Json.Linq
return 0;
}
IJsonLineInfo info = _current;
IJsonLineInfo? info = _current;
if (info != null)
{
return info.LinePosition;
+17 -16
View File
@@ -24,6 +24,7 @@
#endregion
using System;
using System.Diagnostics;
using System.Globalization;
#if HAVE_BIG_INTEGER
using System.Numerics;
@@ -37,22 +38,22 @@ namespace Newtonsoft.Json.Linq
/// </summary>
public partial class JTokenWriter : JsonWriter
{
private JContainer _token;
private JContainer _parent;
private JContainer? _token;
private JContainer? _parent;
// used when writer is writing single value and the value has no containing parent
private JValue _value;
private JToken _current;
private JValue? _value;
private JToken? _current;
/// <summary>
/// Gets the <see cref="JToken"/> at the writer's current position.
/// </summary>
public JToken CurrentToken => _current;
public JToken? CurrentToken => _current;
/// <summary>
/// Gets the token being written.
/// </summary>
/// <value>The token being written.</value>
public JToken Token
public JToken? Token
{
get
{
@@ -131,7 +132,7 @@ namespace Newtonsoft.Json.Linq
private void RemoveParent()
{
_current = _parent;
_parent = _parent.Parent;
_parent = _parent!.Parent;
if (_parent != null && _parent.Type == JTokenType.Property)
{
@@ -186,12 +187,12 @@ namespace Newtonsoft.Json.Linq
base.WritePropertyName(name);
}
private void AddValue(object value, JsonToken token)
private void AddValue(object? value, JsonToken token)
{
AddValue(new JValue(value), token);
}
internal void AddValue(JValue value, JsonToken token)
internal void AddValue(JValue? value, JsonToken token)
{
if (_parent != null)
{
@@ -216,7 +217,7 @@ namespace Newtonsoft.Json.Linq
/// An error will be raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public override void WriteValue(object value)
public override void WriteValue(object? value)
{
#if HAVE_BIG_INTEGER
if (value is BigInteger)
@@ -253,7 +254,7 @@ namespace Newtonsoft.Json.Linq
/// Writes raw JSON.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public override void WriteRaw(string json)
public override void WriteRaw(string? json)
{
base.WriteRaw(json);
AddValue(new JRaw(json), JsonToken.Raw);
@@ -263,7 +264,7 @@ namespace Newtonsoft.Json.Linq
/// Writes a comment <c>/*...*/</c> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public override void WriteComment(string text)
public override void WriteComment(string? text)
{
base.WriteComment(text);
AddValue(JValue.CreateComment(text), JsonToken.Comment);
@@ -273,7 +274,7 @@ namespace Newtonsoft.Json.Linq
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public override void WriteValue(string value)
public override void WriteValue(string? value)
{
base.WriteValue(value);
AddValue(value, JsonToken.String);
@@ -446,7 +447,7 @@ namespace Newtonsoft.Json.Linq
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public override void WriteValue(byte[] value)
public override void WriteValue(byte[]? value)
{
base.WriteValue(value);
AddValue(value, JsonToken.Bytes);
@@ -476,7 +477,7 @@ namespace Newtonsoft.Json.Linq
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public override void WriteValue(Uri value)
public override void WriteValue(Uri? value)
{
base.WriteValue(value);
AddValue(value, JsonToken.String);
@@ -496,7 +497,7 @@ namespace Newtonsoft.Json.Linq
}
}
JToken value = tokenReader.CurrentToken.CloneToken();
JToken value = tokenReader.CurrentToken!.CloneToken();
if (_parent != null)
{
+3 -3
View File
@@ -49,7 +49,7 @@ namespace Newtonsoft.Json.Linq
{
if (converters != null && converters.Length > 0 && _value != null)
{
JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType());
JsonConverter? matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType());
if (matchingConverter != null && matchingConverter.CanWrite)
{
// TODO: Call WriteJsonAsync when it exists.
@@ -121,13 +121,13 @@ namespace Newtonsoft.Json.Linq
return writer.WriteValueAsync(Convert.ToDateTime(_value, CultureInfo.InvariantCulture), cancellationToken);
case JTokenType.Bytes:
return writer.WriteValueAsync((byte[])_value, cancellationToken);
return writer.WriteValueAsync((byte[]?)_value, cancellationToken);
case JTokenType.Guid:
return writer.WriteValueAsync(_value != null ? (Guid?)_value : null, cancellationToken);
case JTokenType.TimeSpan:
return writer.WriteValueAsync(_value != null ? (TimeSpan?)_value : null, cancellationToken);
case JTokenType.Uri:
return writer.WriteValueAsync((Uri)_value, cancellationToken);
return writer.WriteValueAsync((Uri?)_value, cancellationToken);
}
throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(Type), _valueType, "Unexpected token type.");
+35 -28
View File
@@ -28,6 +28,8 @@ using System.Collections.Generic;
using System.Diagnostics;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
#if HAVE_DYNAMIC
using System.Dynamic;
using System.Linq.Expressions;
@@ -47,9 +49,9 @@ namespace Newtonsoft.Json.Linq
#endif
{
private JTokenType _valueType;
private object _value;
private object? _value;
internal JValue(object value, JTokenType type)
internal JValue(object? value, JTokenType type)
{
_value = value;
_valueType = type;
@@ -188,7 +190,7 @@ namespace Newtonsoft.Json.Linq
/// Initializes a new instance of the <see cref="JValue"/> class with the given value.
/// </summary>
/// <param name="value">The value.</param>
public JValue(object value)
public JValue(object? value)
: this(value, GetValueType(null, value))
{
}
@@ -241,7 +243,7 @@ namespace Newtonsoft.Json.Linq
}
#endif
internal static int Compare(JTokenType valueType, object objA, object objB)
internal static int Compare(JTokenType valueType, object? objA, object? objB)
{
if (objA == objB)
{
@@ -267,8 +269,8 @@ namespace Newtonsoft.Json.Linq
}
if (objB is BigInteger integerB)
{
return -CompareBigInteger(integerB, objA);
}
return -CompareBigInteger(integerB, objA);
}
#endif
if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
{
@@ -300,7 +302,7 @@ namespace Newtonsoft.Json.Linq
return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
}
return CompareFloat(objA, objB);
}
}
case JTokenType.Comment:
case JTokenType.String:
case JTokenType.Raw:
@@ -353,10 +355,10 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Object must be of type byte[].");
}
byte[] bytesA = objA as byte[];
byte[]? bytesA = objA as byte[];
Debug.Assert(bytesA != null);
return MiscellaneousUtils.ByteArrayCompare(bytesA, bytesB);
return MiscellaneousUtils.ByteArrayCompare(bytesA!, bytesB);
case JTokenType.Guid:
if (!(objB is Guid))
{
@@ -368,7 +370,7 @@ namespace Newtonsoft.Json.Linq
return guid1.CompareTo(guid2);
case JTokenType.Uri:
Uri uri2 = objB as Uri;
Uri? uri2 = objB as Uri;
if (uri2 == null)
{
throw new ArgumentException("Object must be of type Uri.");
@@ -407,7 +409,7 @@ namespace Newtonsoft.Json.Linq
}
#if HAVE_EXPRESSIONS
private static bool Operation(ExpressionType operation, object objA, object objB, out object result)
private static bool Operation(ExpressionType operation, object? objA, object? objB, out object? result)
{
if (objA is string || objB is string)
{
@@ -564,7 +566,7 @@ namespace Newtonsoft.Json.Linq
/// </summary>
/// <param name="value">The value.</param>
/// <returns>A <see cref="JValue"/> comment with the given value.</returns>
public static JValue CreateComment(string value)
public static JValue CreateComment(string? value)
{
return new JValue(value, JTokenType.Comment);
}
@@ -597,7 +599,7 @@ namespace Newtonsoft.Json.Linq
return new JValue(null, JTokenType.Undefined);
}
private static JTokenType GetValueType(JTokenType? current, object value)
private static JTokenType GetValueType(JTokenType? current, object? value)
{
if (value == null)
{
@@ -694,13 +696,13 @@ namespace Newtonsoft.Json.Linq
/// Gets or sets the underlying token value.
/// </summary>
/// <value>The underlying token value.</value>
public object Value
public object? Value
{
get => _value;
set
{
Type currentType = _value?.GetType();
Type newType = value?.GetType();
Type? currentType = _value?.GetType();
Type? newType = value?.GetType();
if (currentType != newType)
{
@@ -720,7 +722,7 @@ namespace Newtonsoft.Json.Linq
{
if (converters != null && converters.Length > 0 && _value != null)
{
JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType());
JsonConverter? matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType());
if (matchingConverter != null && matchingConverter.CanWrite)
{
matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault());
@@ -803,7 +805,7 @@ namespace Newtonsoft.Json.Linq
}
return;
case JTokenType.Bytes:
writer.WriteValue((byte[])_value);
writer.WriteValue((byte[]?)_value);
return;
case JTokenType.Guid:
writer.WriteValue((_value != null) ? (Guid?)_value : null);
@@ -812,7 +814,7 @@ namespace Newtonsoft.Json.Linq
writer.WriteValue((_value != null) ? (TimeSpan?)_value : null);
return;
case JTokenType.Uri:
writer.WriteValue((Uri)_value);
writer.WriteValue((Uri?)_value);
return;
}
@@ -839,7 +841,7 @@ namespace Newtonsoft.Json.Linq
/// <c>true</c> if the current object is equal to the <paramref name="other"/> parameter; otherwise, <c>false</c>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(JValue other)
public bool Equals([AllowNull] JValue other)
{
if (other == null)
{
@@ -858,7 +860,12 @@ namespace Newtonsoft.Json.Linq
/// </returns>
public override bool Equals(object obj)
{
return Equals(obj as JValue);
if (obj is JValue v)
{
return Equals(v);
}
return false;
}
/// <summary>
@@ -925,7 +932,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)
{
@@ -957,7 +964,7 @@ namespace Newtonsoft.Json.Linq
private class JValueDynamicProxy : DynamicProxy<JValue>
{
public override bool TryConvert(JValue instance, ConvertBinder binder, out object result)
public override bool TryConvert(JValue instance, ConvertBinder binder, [NotNullWhen(true)]out object? result)
{
if (binder.Type == typeof(JValue) || binder.Type == typeof(JToken))
{
@@ -965,7 +972,7 @@ namespace Newtonsoft.Json.Linq
return true;
}
object value = instance.Value;
object? value = instance.Value;
if (value == null)
{
@@ -977,9 +984,9 @@ namespace Newtonsoft.Json.Linq
return true;
}
public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, out object result)
public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, [NotNullWhen(true)]out object? result)
{
object compareValue = arg is JValue value ? value.Value : arg;
object? compareValue = arg is JValue value ? value.Value : arg;
switch (binder.Operation)
{
@@ -1031,7 +1038,7 @@ namespace Newtonsoft.Json.Linq
}
JTokenType comparisonType;
object otherValue;
object? otherValue;
if (obj is JValue value)
{
otherValue = value.Value;
@@ -1166,7 +1173,7 @@ namespace Newtonsoft.Json.Linq
return (DateTime)this;
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
object? IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return ToObject(conversionType);
}
@@ -14,7 +14,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
if (Index != null)
{
JToken v = GetTokenIndex(t, errorWhenNoMatch, Index.GetValueOrDefault());
JToken? v = GetTokenIndex(t, errorWhenNoMatch, Index.GetValueOrDefault());
if (v != null)
{
@@ -4,7 +4,12 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
internal class ArrayMultipleIndexFilter : PathFilter
{
public List<int> Indexes { get; set; }
internal List<int> Indexes;
public ArrayMultipleIndexFilter(List<int> indexes)
{
Indexes = indexes;
}
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
@@ -12,7 +17,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
foreach (int i in Indexes)
{
JToken v = GetTokenIndex(t, errorWhenNoMatch, i);
JToken? v = GetTokenIndex(t, errorWhenNoMatch, i);
if (v != null)
{
@@ -6,7 +6,12 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
internal class FieldFilter : PathFilter
{
public string Name { get; set; }
internal string? Name;
public FieldFilter(string? name)
{
Name = name;
}
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
@@ -16,7 +21,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
if (Name != null)
{
JToken v = o[Name];
JToken? v = o[Name];
if (v != null)
{
@@ -29,9 +34,9 @@ namespace Newtonsoft.Json.Linq.JsonPath
}
else
{
foreach (KeyValuePair<string, JToken> p in o)
foreach (KeyValuePair<string, JToken?> p in o)
{
yield return p.Value;
yield return p.Value!;
}
}
}
@@ -11,7 +11,12 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
internal class FieldMultipleFilter : PathFilter
{
public List<string> Names { get; set; }
internal List<string> Names;
public FieldMultipleFilter(List<string> names)
{
Names = names;
}
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
@@ -21,7 +26,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
foreach (string name in Names)
{
JToken v = o[name];
JToken? v = o[name];
if (v != null)
{
+27 -39
View File
@@ -107,7 +107,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
case '(':
if (_currentIndex > currentPartStartIndex)
{
string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex);
string? member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex);
if (member == "*")
{
member = null;
@@ -136,7 +136,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
case '.':
if (_currentIndex > currentPartStartIndex)
{
string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex);
string? member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex);
if (member == "*")
{
member = null;
@@ -177,7 +177,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
if (_currentIndex > currentPartStartIndex)
{
string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd();
string? member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd();
if (member == "*")
{
member = null;
@@ -196,9 +196,9 @@ namespace Newtonsoft.Json.Linq.JsonPath
return atPathEnd;
}
private static PathFilter CreatePathFilter(string member, bool scan)
private static PathFilter CreatePathFilter(string? member, bool scan)
{
PathFilter filter = (scan) ? (PathFilter)new ScanFilter {Name = member} : new FieldFilter {Name = member};
PathFilter filter = (scan) ? (PathFilter)new ScanFilter(member) : new FieldFilter(member);
return filter;
}
@@ -230,7 +230,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
int start = _currentIndex;
int? end = null;
List<int> indexes = null;
List<int>? indexes = null;
int colonCount = 0;
int? startIndex = null;
int? endIndex = null;
@@ -262,7 +262,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);
indexes.Add(index);
return new ArrayMultipleIndexFilter { Indexes = indexes };
return new ArrayMultipleIndexFilter(indexes);
}
else if (colonCount > 0)
{
@@ -421,26 +421,19 @@ namespace Newtonsoft.Json.Linq.JsonPath
if (!scan)
{
return new QueryFilter
{
Expression = expression
};
return new QueryFilter(expression);
}
else
{
return new QueryScanFilter
{
Expression = expression
};
return new QueryScanFilter(expression);
}
}
private bool TryParseExpression(out List<PathFilter> expressionPath)
private bool TryParseExpression(out List<PathFilter>? expressionPath)
{
if (_expression[_currentIndex] == '$')
{
expressionPath = new List<PathFilter>();
expressionPath.Add(RootFilter.Instance);
expressionPath = new List<PathFilter> { RootFilter.Instance };
}
else if (_expression[_currentIndex] == '@')
{
@@ -454,7 +447,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
_currentIndex++;
if (ParsePath(expressionPath, _currentIndex, true))
if (ParsePath(expressionPath!, _currentIndex, true))
{
throw new JsonException("Path ended with open query.");
}
@@ -471,12 +464,12 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
EatWhitespace();
if (TryParseExpression(out var expressionPath))
if (TryParseExpression(out List<PathFilter>? expressionPath))
{
EatWhitespace();
EnsureLength("Path ended with open query.");
return expressionPath;
return expressionPath!;
}
if (TryParseValue(out var value))
@@ -492,13 +485,13 @@ namespace Newtonsoft.Json.Linq.JsonPath
private QueryExpression ParseExpression()
{
QueryExpression rootExpression = null;
CompositeExpression parentExpression = null;
QueryExpression? rootExpression = null;
CompositeExpression? parentExpression = null;
while (_currentIndex < _expression.Length)
{
object left = ParseSide();
object right = null;
object? right = null;
QueryOperator op;
if (_expression[_currentIndex] == ')'
@@ -514,19 +507,14 @@ namespace Newtonsoft.Json.Linq.JsonPath
right = ParseSide();
}
BooleanQueryExpression booleanExpression = new BooleanQueryExpression
{
Left = left,
Operator = op,
Right = right
};
BooleanQueryExpression booleanExpression = new BooleanQueryExpression(op, left, right);
if (_expression[_currentIndex] == ')')
{
if (parentExpression != null)
{
parentExpression.Expressions.Add(booleanExpression);
return rootExpression;
return rootExpression!;
}
return booleanExpression;
@@ -540,7 +528,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
if (parentExpression == null || parentExpression.Operator != QueryOperator.And)
{
CompositeExpression andExpression = new CompositeExpression { Operator = QueryOperator.And };
CompositeExpression andExpression = new CompositeExpression(QueryOperator.And);
parentExpression?.Expressions.Add(andExpression);
@@ -563,7 +551,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
if (parentExpression == null || parentExpression.Operator != QueryOperator.Or)
{
CompositeExpression orExpression = new CompositeExpression { Operator = QueryOperator.Or };
CompositeExpression orExpression = new CompositeExpression(QueryOperator.Or);
parentExpression?.Expressions.Add(orExpression);
@@ -582,7 +570,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
throw new JsonException("Path ended with open query.");
}
private bool TryParseValue(out object value)
private bool TryParseValue(out object? value)
{
char currentChar = _expression[_currentIndex];
if (currentChar == '\'')
@@ -763,9 +751,9 @@ namespace Newtonsoft.Json.Linq.JsonPath
private bool Match(string s)
{
int currentPosition = _currentIndex;
foreach (char c in s)
for (int i = 0; i < s.Length; i++)
{
if (currentPosition < _expression.Length && _expression[currentPosition] == c)
if (currentPosition < _expression.Length && _expression[currentPosition] == s[i])
{
currentPosition++;
}
@@ -832,7 +820,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
private PathFilter ParseQuotedField(char indexerCloseChar, bool scan)
{
List<string> fields = null;
List<string>? fields = null;
while (_currentIndex < _expression.Length)
{
@@ -847,8 +835,8 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
fields.Add(field);
return (scan)
? (PathFilter)new ScanMultipleFilter { Names = fields }
: (PathFilter)new FieldMultipleFilter { Names = fields };
? (PathFilter)new ScanMultipleFilter(fields)
: (PathFilter)new FieldMultipleFilter(fields);
}
else
{
@@ -8,9 +8,8 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
public abstract IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch);
protected static JToken GetTokenIndex(JToken t, bool errorWhenNoMatch, int index)
protected static JToken? GetTokenIndex(JToken t, bool errorWhenNoMatch, int index)
{
if (t is JArray a)
{
if (a.Count <= index)
@@ -50,7 +49,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
}
}
protected static JToken GetNextScanValue(JToken originalParent, JToken container, JToken value)
protected static JToken? GetNextScanValue(JToken originalParent, JToken? container, JToken? value)
{
// step into container's values
if (container != null && container.HasValues)
@@ -60,7 +59,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
else
{
// finished container, move to parent
while (value != null && value != originalParent && value == value.Parent.Last)
while (value != null && value != originalParent && value == value.Parent!.Last)
{
value = value.Parent;
}
@@ -32,7 +32,12 @@ namespace Newtonsoft.Json.Linq.JsonPath
internal abstract class QueryExpression
{
public QueryOperator Operator { get; set; }
internal QueryOperator Operator;
public QueryExpression(QueryOperator @operator)
{
Operator = @operator;
}
public abstract bool IsMatch(JToken root, JToken t);
}
@@ -41,7 +46,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
public List<QueryExpression> Expressions { get; set; }
public CompositeExpression()
public CompositeExpression(QueryOperator @operator) : base(@operator)
{
Expressions = new List<QueryExpression>();
}
@@ -76,10 +81,16 @@ namespace Newtonsoft.Json.Linq.JsonPath
internal class BooleanQueryExpression : QueryExpression
{
public object Left { get; set; }
public object Right { get; set; }
public readonly object Left;
public readonly object? Right;
private IEnumerable<JToken> GetResult(JToken root, JToken t, object o)
public BooleanQueryExpression(QueryOperator @operator, object left, object? right) : base(@operator)
{
Left = left;
Right = right;
}
private IEnumerable<JToken> GetResult(JToken root, JToken t, object? o)
{
if (o is JToken resultToken)
{
@@ -211,13 +222,13 @@ namespace Newtonsoft.Json.Linq.JsonPath
return false;
}
string regexText = (string)pattern.Value;
string regexText = (string)pattern.Value!;
int patternOptionDelimiterIndex = regexText.LastIndexOf('/');
string patternText = regexText.Substring(1, patternOptionDelimiterIndex - 1);
string optionsText = regexText.Substring(patternOptionDelimiterIndex + 1);
return Regex.IsMatch((string)input.Value, patternText, MiscellaneousUtils.GetRegexOptions(optionsText));
return Regex.IsMatch((string)input.Value!, patternText, MiscellaneousUtils.GetRegexOptions(optionsText));
}
internal static bool EqualsWithStringCoercion(JValue value, JValue queryValue)
@@ -240,7 +251,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
return false;
}
string queryValueString = (string)queryValue.Value;
string queryValueString = (string)queryValue.Value!;
string currentValueString;
@@ -258,21 +269,21 @@ namespace Newtonsoft.Json.Linq.JsonPath
else
#endif
{
DateTimeUtils.WriteDateTimeString(writer, (DateTime)value.Value, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeString(writer, (DateTime)value.Value!, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture);
}
currentValueString = writer.ToString();
}
break;
case JTokenType.Bytes:
currentValueString = Convert.ToBase64String((byte[])value.Value);
currentValueString = Convert.ToBase64String((byte[])value.Value!);
break;
case JTokenType.Guid:
case JTokenType.TimeSpan:
currentValueString = value.Value.ToString();
currentValueString = value.Value!.ToString();
break;
case JTokenType.Uri:
currentValueString = ((Uri)value.Value).OriginalString;
currentValueString = ((Uri)value.Value!).OriginalString;
break;
default:
return false;
@@ -5,7 +5,12 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
internal class QueryFilter : PathFilter
{
public QueryExpression Expression { get; set; }
internal QueryExpression Expression;
public QueryFilter(QueryExpression expression)
{
Expression = expression;
}
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
@@ -5,7 +5,12 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
internal class QueryScanFilter : PathFilter
{
public QueryExpression Expression { get; set; }
internal QueryExpression Expression;
public QueryScanFilter(QueryExpression expression)
{
Expression = expression;
}
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
@@ -4,7 +4,12 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
internal class ScanFilter : PathFilter
{
public string Name { get; set; }
internal string? Name;
public ScanFilter(string? name)
{
Name = name;
}
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
@@ -15,11 +20,11 @@ namespace Newtonsoft.Json.Linq.JsonPath
yield return c;
}
JToken value = c;
JToken? value = c;
while (true)
{
JContainer container = value as JContainer;
JContainer? container = value as JContainer;
value = GetNextScanValue(c, container, value);
if (value == null)
@@ -4,17 +4,22 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
internal class ScanMultipleFilter : PathFilter
{
public List<string> Names { get; set; }
private List<string> _names;
public ScanMultipleFilter(List<string> names)
{
_names = names;
}
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
foreach (JToken c in current)
{
JToken value = c;
JToken? value = c;
while (true)
{
JContainer container = value as JContainer;
JContainer? container = value as JContainer;
value = GetNextScanValue(c, container, value);
if (value == null)
@@ -24,7 +29,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
if (value is JProperty property)
{
foreach (string name in Names)
foreach (string name in _names)
{
if (property.Name == name)
{
@@ -32,7 +37,6 @@ namespace Newtonsoft.Json.Linq.JsonPath
}
}
}
}
}
}
+5 -2
View File
@@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFrameworks Condition="'$(LibraryFrameworks)'==''">net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0;portable-net45+win8+wpa81+wp8;portable-net40+win8+wpa81+wp8+sl5</TargetFrameworks>
<TargetFrameworks Condition="'$(LibraryFrameworks)'!=''">$(LibraryFrameworks)</TargetFrameworks>
<LangVersion>latest</LangVersion>
<LangVersion>8.0</LangVersion>
<!-- version numbers will be updated by build -->
<AssemblyVersion>11.0.0.0</AssemblyVersion>
<FileVersion>11.0.1</FileVersion>
@@ -25,6 +25,7 @@
<RootNamespace>Newtonsoft.Json</RootNamespace>
<AssemblyName>Newtonsoft.Json</AssemblyName>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Nullable>enable</Nullable>
<MinClientVersion>2.12</MinClientVersion>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
@@ -37,7 +38,9 @@
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-18618-05" PrivateAssets="All" />
</ItemGroup>
<!-- Compiler to support nullable in non-preview VS2019 -->
<PackageReference Include="Microsoft.Net.Compilers.Toolset" Version="3.3.0-beta1-final" PrivateAssets="All" />
</ItemGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net45'">
<AssemblyTitle>Json.NET</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_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>
+2
View File
@@ -28,6 +28,8 @@ using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
#nullable disable
namespace Newtonsoft.Json.Schema
{
/// <summary>
+2
View File
@@ -30,6 +30,8 @@ using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Globalization;
#nullable disable
namespace Newtonsoft.Json.Schema
{
/// <summary>
@@ -35,6 +35,8 @@ using System.Globalization;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
#nullable disable
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")]
@@ -26,6 +26,8 @@
using System;
using System.Collections.Generic;
#nullable disable
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")]
@@ -26,6 +26,8 @@
using System;
using System.Runtime.Serialization;
#nullable disable
namespace Newtonsoft.Json.Schema
{
/// <summary>
@@ -37,6 +37,8 @@ using System.Linq;
#endif
#nullable disable
namespace Newtonsoft.Json.Schema
{
/// <summary>
@@ -28,6 +28,8 @@ using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
#nullable disable
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")]
@@ -32,6 +32,8 @@ using System.Linq;
#endif
#nullable disable
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")]
@@ -33,6 +33,8 @@ using System.Linq;
#endif
#nullable disable
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")]
@@ -26,6 +26,8 @@
using System;
using System.Collections.ObjectModel;
#nullable disable
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")]
@@ -32,6 +32,8 @@ using System.Linq;
#endif
#nullable disable
namespace Newtonsoft.Json.Schema
{
/// <summary>
@@ -25,6 +25,8 @@
using System;
#nullable disable
namespace Newtonsoft.Json.Schema
{
/// <summary>
@@ -35,6 +35,8 @@ using System.Linq;
#endif
#nullable disable
namespace Newtonsoft.Json.Schema
{
[Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")]

Some files were not shown because too many files have changed in this diff Show More