From f7e7bd05d9280f17993500085202ff4ea150564a Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Wed, 31 Mar 2021 15:57:25 +1300 Subject: [PATCH 01/30] Fix MaxDepth when used with ToObject inside of a JsonConverter (#2505) --- Src/Newtonsoft.Json.Tests/Issues/Issue2504.cs | 121 ++++++++++++++++++ .../JsonTextReaderTests/ReadAsyncTests.cs | 39 ++++++ .../JsonTextReaderTests/ReadTests.cs | 39 ++++++ .../Serialization/JsonSerializerTest.cs | 58 +++++++++ Src/Newtonsoft.Json.Tests/TestFixtureBase.cs | 16 +++ Src/Newtonsoft.Json/JsonReader.cs | 2 +- Src/Newtonsoft.Json/JsonSerializer.cs | 4 +- Src/Newtonsoft.Json/JsonSerializerSettings.cs | 2 +- Src/Newtonsoft.Json/Linq/JToken.cs | 8 ++ .../Serialization/JsonSerializerProxy.cs | 2 +- .../Serialization/TraceJsonReader.cs | 2 +- 11 files changed, 287 insertions(+), 6 deletions(-) create mode 100644 Src/Newtonsoft.Json.Tests/Issues/Issue2504.cs diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2504.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2504.cs new file mode 100644 index 000000000..4363a9112 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2504.cs @@ -0,0 +1,121 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +#if (NET45 || NET50) +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif +using System.Collections.Generic; +using Newtonsoft.Json.Serialization; +using Newtonsoft.Json.Converters; +using System.Collections; +using System; +using System.IO; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Issues +{ + [TestFixture] + public class Issue2504 : TestFixtureBase + { + [Test] + public void Test() + { + string jsontext = GetNestedJson(150); + + var o = JsonConvert.DeserializeObject(jsontext, new JsonSerializerSettings + { + Converters = new List { new TestConverter() }, + MaxDepth = 150 + }); + + Assert.AreEqual(150, GetDepth(o.Children)); + } + + [Test] + public void Test_Failure() + { + string jsontext = GetNestedJson(150); + + string expectedMessage = @"The reader's MaxDepth of 100 has been exceeded. Path '0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99', line 101, position 207."; + + ExceptionAssert.Throws(() => JsonConvert.DeserializeObject(jsontext, new JsonSerializerSettings + { + Converters = new List { new TestConverter() }, + MaxDepth = 100 + }), expectedMessage); + } + + private static int GetDepth(JToken o) + { + int depth = 1; + while (o.First != null) + { + o = o.First; + if (o.Type == JTokenType.Object) + { + depth++; + } + } + + return depth; + } + + private class TestObject + { + public JToken Children { get; set; } + } + + private class TestConverter : JsonConverter + { + public override bool CanConvert(Type objectType) + { + return objectType == typeof(TestObject); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + JToken token = JToken.Load(reader); + + var newToken = token.ToObject(serializer); + + return new TestObject + { + Children = newToken + }; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + throw new NotImplementedException(); + } + } + } +} +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadAsyncTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadAsyncTests.cs index 7f23c53d8..770b77363 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadAsyncTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadAsyncTests.cs @@ -1776,6 +1776,45 @@ public async Task ThrowOnDuplicateKeysDeserializingAsync() JsonTextReader reader = new JsonTextReader(new StringReader(json)); await ExceptionAssert.ThrowsAsync(async () => await JToken.ReadFromAsync(reader, settings)); } + + [Test] + public async Task MaxDepth_GreaterThanDefaultAsync() + { + string json = GetNestedJson(150); + + JsonTextReader reader = new JsonTextReader(new StringReader(json)); + reader.MaxDepth = 150; + + while (await reader.ReadAsync()) + { + } + } + + [Test] + public async Task MaxDepth_NullAsync() + { + string json = GetNestedJson(150); + + JsonTextReader reader = new JsonTextReader(new StringReader(json)); + reader.MaxDepth = null; + + while (await reader.ReadAsync()) + { + } + } + + [Test] + public async Task MaxDepth_MaxValueAsync() + { + string json = GetNestedJson(150); + + JsonTextReader reader = new JsonTextReader(new StringReader(json)); + reader.MaxDepth = int.MaxValue; + + while (await reader.ReadAsync()) + { + } + } } } #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadTests.cs index 905dbbed5..5a8bd1af1 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadTests.cs @@ -1770,5 +1770,44 @@ public void ThrowOnDuplicateKeysDeserializing() JToken.ReadFrom(reader, settings); }); } + + [Test] + public void MaxDepth_GreaterThanDefault() + { + string json = GetNestedJson(150); + + JsonTextReader reader = new JsonTextReader(new StringReader(json)); + reader.MaxDepth = 150; + + while (reader.Read()) + { + } + } + + [Test] + public void MaxDepth_Null() + { + string json = GetNestedJson(150); + + JsonTextReader reader = new JsonTextReader(new StringReader(json)); + reader.MaxDepth = null; + + while (reader.Read()) + { + } + } + + [Test] + public void MaxDepth_MaxValue() + { + string json = GetNestedJson(150); + + JsonTextReader reader = new JsonTextReader(new StringReader(json)); + reader.MaxDepth = int.MaxValue; + + while (reader.Read()) + { + } + } } } diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs index 6ad965a35..6ca78fb3e 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs @@ -8032,5 +8032,63 @@ public void SetMaxDepth_DepthNotExceeded() Assert.AreEqual(64, reader.MaxDepth); } + + [Test] + public void SetMaxDepth_DefaultDepthExceeded() + { + string json = GetNestedJson(150); + + ExceptionAssert.Throws( + () => JsonConvert.DeserializeObject(json), + "The reader's MaxDepth of 64 has been exceeded. Path '0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63', line 65, position 135."); + } + + [Test] + public void SetMaxDepth_IncreasedDepthNotExceeded() + { + string json = GetNestedJson(150); + + JObject o = JsonConvert.DeserializeObject(json, new JsonSerializerSettings { MaxDepth = 150 }); + int depth = GetDepth(o); + + Assert.AreEqual(150, depth); + } + + [Test] + public void SetMaxDepth_NullDepthNotExceeded() + { + string json = GetNestedJson(150); + + JObject o = JsonConvert.DeserializeObject(json, new JsonSerializerSettings { MaxDepth = null }); + int depth = GetDepth(o); + + Assert.AreEqual(150, depth); + } + + [Test] + public void SetMaxDepth_MaxValueDepthNotExceeded() + { + string json = GetNestedJson(150); + + JObject o = JsonConvert.DeserializeObject(json, new JsonSerializerSettings { MaxDepth = int.MaxValue }); + int depth = GetDepth(o); + + Assert.AreEqual(150, depth); + } + + private static int GetDepth(JToken o) + { + int depth = 1; + while (o.First != null) + { + o = o.First; + if (o.Type == JTokenType.Object) + { + depth++; + } + } + + return depth; + } } } diff --git a/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs b/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs index 52c5ed354..7611f2092 100644 --- a/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs +++ b/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs @@ -36,6 +36,7 @@ #endif using System.Text; using System.Threading; +using Newtonsoft.Json.Linq; #if DNXCORE50 using Xunit; using Assert = Newtonsoft.Json.Tests.XUnitAssert; @@ -306,6 +307,21 @@ protected string EscapeJson(string json) { return @"@""" + json.Replace(@"""", @"""""") + @""""; } + + protected string GetNestedJson(int depth) + { + JObject root = new JObject(); + JObject current = root; + for (int i = 0; i < depth - 1; i++) + { + JObject nested = new JObject(); + current[i.ToString()] = nested; + + current = nested; + } + + return root.ToString(); + } } public static class CustomAssert diff --git a/Src/Newtonsoft.Json/JsonReader.cs b/Src/Newtonsoft.Json/JsonReader.cs index b94c63eae..2351b1879 100644 --- a/Src/Newtonsoft.Json/JsonReader.cs +++ b/Src/Newtonsoft.Json/JsonReader.cs @@ -228,7 +228,7 @@ public string? DateFormatString /// /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . /// A null value means there is no maximum. - /// The default value is 128. + /// The default value is 64. /// public int? MaxDepth { diff --git a/Src/Newtonsoft.Json/JsonSerializer.cs b/Src/Newtonsoft.Json/JsonSerializer.cs index 23f5c6b62..13e3a9c68 100644 --- a/Src/Newtonsoft.Json/JsonSerializer.cs +++ b/Src/Newtonsoft.Json/JsonSerializer.cs @@ -514,7 +514,7 @@ public virtual CultureInfo Culture /// /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . /// A null value means there is no maximum. - /// The default value is 128. + /// The default value is 64. /// public virtual int? MaxDepth { @@ -913,7 +913,7 @@ internal virtual void PopulateInternal(JsonReader reader, object target) 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) + internal 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)) { diff --git a/Src/Newtonsoft.Json/JsonSerializerSettings.cs b/Src/Newtonsoft.Json/JsonSerializerSettings.cs index bc0cd5a7b..fc5205dd2 100644 --- a/Src/Newtonsoft.Json/JsonSerializerSettings.cs +++ b/Src/Newtonsoft.Json/JsonSerializerSettings.cs @@ -326,7 +326,7 @@ public string DateFormatString /// /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . /// A null value means there is no maximum. - /// The default value is 128. + /// The default value is 64. /// public int? MaxDepth { diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index d1f6c451f..ff4aaf938 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -45,6 +45,7 @@ #else using System.Linq; #endif +using Newtonsoft.Json.Serialization; namespace Newtonsoft.Json.Linq { @@ -2079,6 +2080,13 @@ public static JToken FromObject(object o, JsonSerializer jsonSerializer) using (JTokenReader jsonReader = new JTokenReader(this)) { + // Hacky fix to ensure the serializer settings are set onto the new reader. + // This is required because the serializer won't update settings when used inside of a converter. + if (jsonSerializer is JsonSerializerProxy proxy) + { + proxy._serializer.SetupReader(jsonReader, out _, out _, out _, out _, out _, out _); + } + return jsonSerializer.Deserialize(jsonReader, objectType); } } diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs index fc8e26fd8..a122fe001 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs @@ -36,7 +36,7 @@ internal class JsonSerializerProxy : JsonSerializer { private readonly JsonSerializerInternalReader? _serializerReader; private readonly JsonSerializerInternalWriter? _serializerWriter; - private readonly JsonSerializer _serializer; + internal readonly JsonSerializer _serializer; public override event EventHandler? Error { diff --git a/Src/Newtonsoft.Json/Serialization/TraceJsonReader.cs b/Src/Newtonsoft.Json/Serialization/TraceJsonReader.cs index 04bc99ea3..53ab49777 100644 --- a/Src/Newtonsoft.Json/Serialization/TraceJsonReader.cs +++ b/Src/Newtonsoft.Json/Serialization/TraceJsonReader.cs @@ -138,7 +138,7 @@ public override char QuoteChar public override object? Value => _innerReader.Value; - public override Type ?ValueType => _innerReader.ValueType; + public override Type? ValueType => _innerReader.ValueType; public override void Close() { From 2b0f7a2492bbedbf5e381d0468f503a99e834dbc Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Sat, 15 May 2021 11:40:11 +1200 Subject: [PATCH 02/30] Fix deserializing mistmatched JToken types in properties (#2530) --- Src/Newtonsoft.Json.Tests/Issues/Issue2529.cs | 61 +++++++++++++++++++ .../JsonSerializerInternalReader.cs | 3 +- 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 Src/Newtonsoft.Json.Tests/Issues/Issue2529.cs diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2529.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2529.cs new file mode 100644 index 000000000..5d7cb7b9d --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2529.cs @@ -0,0 +1,61 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +#if (NET45 || NET50) +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif +using System.Collections.Generic; +using Newtonsoft.Json.Serialization; +using Newtonsoft.Json.Converters; +using System.Collections; +using System; +using System.IO; +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Issues +{ + [TestFixture] + public class Issue2529 : TestFixtureBase + { + [Test] + public void Test() + { + Something something = JsonConvert.DeserializeObject("{ \"foo\": [] }"); + + Assert.AreEqual(JTokenType.Array, something.Foo.Type); + } + + private class Something + { + public JToken Foo { get; set; } = JValue.CreateNull(); + } + } +} +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 53b39030e..df77f51ff 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -1113,7 +1113,8 @@ private bool CalculatePropertyDetails( if ((objectCreationHandling != ObjectCreationHandling.Replace) && (tokenType == JsonToken.StartArray || tokenType == JsonToken.StartObject || propertyConverter != null) - && property.Readable) + && property.Readable + && property.PropertyContract?.ContractType != JsonContractType.Linq) { currentValue = property.ValueProvider!.GetValue(target); gottenCurrentValue = true; From e44ab3348fabcbe9ed6b5053b706a9e10b945ba1 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Sat, 15 May 2021 13:45:00 +1200 Subject: [PATCH 03/30] Fix merging enumerable content and validate content (#2531) --- Src/Newtonsoft.Json.Tests/Linq/MergeTests.cs | 44 +++++++++++++++ Src/Newtonsoft.Json/Linq/JContainer.cs | 58 +++++++++++++++----- 2 files changed, 88 insertions(+), 14 deletions(-) diff --git a/Src/Newtonsoft.Json.Tests/Linq/MergeTests.cs b/Src/Newtonsoft.Json.Tests/Linq/MergeTests.cs index 7108c92e1..db660052d 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/MergeTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/MergeTests.cs @@ -46,6 +46,18 @@ namespace Newtonsoft.Json.Tests.Linq [TestFixture] public class MergeTests : TestFixtureBase { + [Test] + public void MergeInvalidObject() + { + var a = new JObject(); + + ExceptionAssert.Throws( + () => a.Merge(new Version()), + @"Could not determine JSON object type for type System.Version. +Parameter name: content", + @"Could not determine JSON object type for type System.Version. (Parameter 'content')"); + } + [Test] public void MergeArraySelf() { @@ -70,6 +82,38 @@ public void MergeObjectSelf() }, a); } + [Test] + public void MergeArrayIntoArray_Replace() + { + var a = new JArray { "1", "2" }; + a.Merge(new string[] { "3", "4" }, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace }); + Assert.AreEqual(new JArray { "3", "4" }, a); + } + + [Test] + public void MergeArrayIntoArray_Concat() + { + var a = new JArray { "1", "2" }; + a.Merge(new string[] { "3", "4" }, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Concat }); + Assert.AreEqual(new JArray { "1", "2", "3", "4" }, a); + } + + [Test] + public void MergeArrayIntoArray_Union() + { + var a = new JArray { "1", "2" }; + a.Merge(new string[] { "2", "3", "4" }, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union }); + Assert.AreEqual(new JArray { "1", "2", "3", "4" }, a); + } + + [Test] + public void MergeArrayIntoArray_Merge() + { + var a = new JArray { "1", "2" }; + a.Merge(new string[] { "2" }, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Merge }); + Assert.AreEqual(new JArray { "2", "2" }, a); + } + [Test] public void MergeNullString() { diff --git a/Src/Newtonsoft.Json/Linq/JContainer.cs b/Src/Newtonsoft.Json/Linq/JContainer.cs index 945de5c7b..07f833bd3 100644 --- a/Src/Newtonsoft.Json/Linq/JContainer.cs +++ b/Src/Newtonsoft.Json/Linq/JContainer.cs @@ -723,8 +723,14 @@ public void RemoveAll() /// Merge the specified content into this . /// /// The content to be merged. - public void Merge(object content) + public void Merge(object? content) { + if (content == null) + { + return; + } + + ValidateContent(content); MergeItem(content, null); } @@ -733,11 +739,31 @@ public void Merge(object content) /// /// The content to be merged. /// The used to merge the content. - public void Merge(object content, JsonMergeSettings? settings) + public void Merge(object? content, JsonMergeSettings? settings) { + if (content == null) + { + return; + } + + ValidateContent(content); MergeItem(content, settings); } + private void ValidateContent(object content) + { + if (content.GetType().IsSubclassOf(typeof(JToken))) + { + return; + } + if (IsMultiContent(content)) + { + return; + } + + throw new ArgumentException("Could not determine JSON object type for type {0}.".FormatWith(CultureInfo.InvariantCulture, content.GetType()), nameof(content)); + } + internal void ReadTokenFrom(JsonReader reader, JsonLoadSettings? options) { int startDepth = reader.Depth; @@ -1141,20 +1167,22 @@ internal static void MergeEnumerableContent(JContainer target, IEnumerable conte switch (settings?.MergeArrayHandling ?? MergeArrayHandling.Concat) { case MergeArrayHandling.Concat: - foreach (JToken item in content) + foreach (object item in content) { - target.Add(item); + target.Add(CreateFromContent(item)); } break; case MergeArrayHandling.Union: #if HAVE_HASH_SET HashSet items = new HashSet(target, EqualityComparer); - foreach (JToken item in content) + foreach (object item in content) { - if (items.Add(item)) + JToken contentItem = CreateFromContent(item); + + if (items.Add(contentItem)) { - target.Add(item); + target.Add(contentItem); } } #else @@ -1164,12 +1192,14 @@ internal static void MergeEnumerableContent(JContainer target, IEnumerable conte items[t] = true; } - foreach (JToken item in content) + foreach (object item in content) { - if (!items.ContainsKey(item)) + JToken contentItem = CreateFromContent(item); + + if (!items.ContainsKey(contentItem)) { - items[item] = true; - target.Add(item); + items[contentItem] = true; + target.Add(contentItem); } } #endif @@ -1180,9 +1210,9 @@ internal static void MergeEnumerableContent(JContainer target, IEnumerable conte break; } target.ClearItems(); - foreach (JToken item in content) + foreach (object item in content) { - target.Add(item); + target.Add(CreateFromContent(item)); } break; case MergeArrayHandling.Merge: @@ -1211,7 +1241,7 @@ internal static void MergeEnumerableContent(JContainer target, IEnumerable conte } else { - target.Add(targetItem); + target.Add(CreateFromContent(targetItem)); } i++; From c9e12bc4755c786a9073dddf1be14cd27823a498 Mon Sep 17 00:00:00 2001 From: Andrew Arnott Date: Fri, 23 Jul 2021 04:21:06 -0600 Subject: [PATCH 04/30] Add nullable annotation to `JToken.ToObject(Type, JsonSerializer)` --- Src/Newtonsoft.Json/Linq/JToken.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index ff4aaf938..9cb008ae2 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -2074,7 +2074,7 @@ public static JToken FromObject(object o, JsonSerializer jsonSerializer) /// The object type that the token will be deserialized to. /// The that will be used when creating the object. /// The new object created from the JSON value. - public object? ToObject(Type objectType, JsonSerializer jsonSerializer) + public object? ToObject(Type? objectType, JsonSerializer jsonSerializer) { ValidationUtils.ArgumentNotNull(jsonSerializer, nameof(jsonSerializer)); @@ -2755,4 +2755,4 @@ internal void CopyAnnotations(JToken target, JToken source) } } } -} \ No newline at end of file +} From 52e257ee57899296d81a868b32300f0b3cfeacbe Mon Sep 17 00:00:00 2001 From: Claire Novotny Date: Sat, 24 Jul 2021 00:06:22 -0400 Subject: [PATCH 05/30] Use latest SDK for reproducible builds (#2557) --- Build/build.ps1 | 4 ++-- Src/global.json | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Build/build.ps1 b/Build/build.ps1 index ea2c22f8e..1beda3451 100644 --- a/Build/build.ps1 +++ b/Build/build.ps1 @@ -14,7 +14,7 @@ $workingName = if ($workingName) {$workingName} else {"Working"} $assemblyVersion = if ($assemblyVersion) {$assemblyVersion} else {$majorVersion + '.0.0'} $netCliChannel = "Current" - $netCliVersion = "5.0.200" + $netCliVersion = "5.0.300" $nugetUrl = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" $ensureNetCliSdk = $true @@ -326,4 +326,4 @@ function Execute-Command($command) { $currentRetry = $currentRetry + 1 } } while (!$success) -} \ No newline at end of file +} diff --git a/Src/global.json b/Src/global.json index 6d19c9f6c..a601da31b 100644 --- a/Src/global.json +++ b/Src/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "5.0.200" + "version": "5.0.300" } -} \ No newline at end of file +} From 4fda2ea27e1f634a53d033d78ea11325dee16ea8 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Sat, 13 Nov 2021 11:07:47 +1300 Subject: [PATCH 06/30] Add embedded README.md (#2596) --- Build/build.ps1 | 4 +- Build/version.json | 2 +- Src/Newtonsoft.Json/Newtonsoft.Json.csproj | 6 +- Src/Newtonsoft.Json/README.md | 71 ++++++++++++++++++++++ Src/global.json | 2 +- azure-pipelines.yml | 19 ++++++ 6 files changed, 98 insertions(+), 6 deletions(-) create mode 100644 Src/Newtonsoft.Json/README.md diff --git a/Build/build.ps1 b/Build/build.ps1 index 1beda3451..718de33c1 100644 --- a/Build/build.ps1 +++ b/Build/build.ps1 @@ -1,7 +1,7 @@ properties { $zipFileName = "Json130r3.zip" $majorVersion = "13.0" - $majorWithReleaseVersion = "13.0.1" + $majorWithReleaseVersion = "13.0.2" $nugetPrerelease = $null $version = GetVersion $majorWithReleaseVersion $packageId = "Newtonsoft.Json" @@ -14,7 +14,7 @@ $workingName = if ($workingName) {$workingName} else {"Working"} $assemblyVersion = if ($assemblyVersion) {$assemblyVersion} else {$majorVersion + '.0.0'} $netCliChannel = "Current" - $netCliVersion = "5.0.300" + $netCliVersion = "6.0.100" $nugetUrl = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" $ensureNetCliSdk = $true diff --git a/Build/version.json b/Build/version.json index 4589a2d6f..7e0f6ad33 100644 --- a/Build/version.json +++ b/Build/version.json @@ -1,6 +1,6 @@ { "Major": 13, - "Release": 1, + "Release": 2, "Prerelease": null, "Assembly": null } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index 4dd7b55a0..6f4bea65f 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -18,8 +18,9 @@ Json.NET Newtonsoft.Json json + README.md packageIcon.png - $(MSBuildThisFileDirectory)packageIcon.png + https://www.newtonsoft.com/content/images/nugeticon.png https://www.newtonsoft.com/json MIT true @@ -36,7 +37,8 @@ - + + diff --git a/Src/Newtonsoft.Json/README.md b/Src/Newtonsoft.Json/README.md new file mode 100644 index 000000000..9982a45ca --- /dev/null +++ b/Src/Newtonsoft.Json/README.md @@ -0,0 +1,71 @@ +# ![Logo](https://raw.githubusercontent.com/JamesNK/Newtonsoft.Json/master/Doc/icons/logo.jpg) Json.NET + +[![NuGet version (Newtonsoft.Json)](https://img.shields.io/nuget/v/Newtonsoft.Json.svg?style=flat-square)](https://www.nuget.org/packages/Newtonsoft.Json/) +[![Build status](https://dev.azure.com/jamesnk/Public/_apis/build/status/JamesNK.Newtonsoft.Json?branchName=master)](https://dev.azure.com/jamesnk/Public/_build/latest?definitionId=8) + +Json.NET is a popular high-performance JSON framework for .NET + +## Serialize JSON + +```csharp +Product product = new Product(); +product.Name = "Apple"; +product.Expiry = new DateTime(2008, 12, 28); +product.Sizes = new string[] { "Small" }; + +string json = JsonConvert.SerializeObject(product); +// { +// "Name": "Apple", +// "Expiry": "2008-12-28T00:00:00", +// "Sizes": [ +// "Small" +// ] +// } +``` + +## Deserialize JSON + +```csharp +string json = @"{ + 'Name': 'Bad Boys', + 'ReleaseDate': '1995-4-7T00:00:00', + 'Genres': [ + 'Action', + 'Comedy' + ] +}"; + +Movie m = JsonConvert.DeserializeObject(json); + +string name = m.Name; +// Bad Boys +``` + +## LINQ to JSON + +```csharp +JArray array = new JArray(); +array.Add("Manual text"); +array.Add(new DateTime(2000, 5, 23)); + +JObject o = new JObject(); +o["MyArray"] = array; + +string json = o.ToString(); +// { +// "MyArray": [ +// "Manual text", +// "2000-05-23T00:00:00" +// ] +// } +``` + +## Links + +- [Homepage](https://www.newtonsoft.com/json) +- [Documentation](https://www.newtonsoft.com/json/help) +- [NuGet Package](https://www.nuget.org/packages/Newtonsoft.Json) +- [Release Notes](https://github.com/JamesNK/Newtonsoft.Json/releases) +- [Contributing Guidelines](https://github.com/JamesNK/Newtonsoft.Json/blob/master/CONTRIBUTING.md) +- [License](https://github.com/JamesNK/Newtonsoft.Json/blob/master/LICENSE.md) +- [Stack Overflow](https://stackoverflow.com/questions/tagged/json.net) diff --git a/Src/global.json b/Src/global.json index a601da31b..047020849 100644 --- a/Src/global.json +++ b/Src/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "5.0.300" + "version": "6.0.100" } } diff --git a/azure-pipelines.yml b/azure-pipelines.yml index e946ce434..85e6cfa73 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -6,6 +6,25 @@ pool: vmImage: 'windows-2019' steps: +- task: UseDotNet@2 + inputs: + version: '6.0.x' + +- task: UseDotNet@2 + inputs: + version: '2.1.x' + packageType: runtime + +- task: UseDotNet@2 + inputs: + version: '3.1.x' + packageType: runtime + +- task: UseDotNet@2 + inputs: + version: '5.0.x' + packageType: runtime + - powershell: | dotnet --info displayName: 'Dotnet installs' From 233ed3a961025fa5bddbcc437a9f300f5467923a Mon Sep 17 00:00:00 2001 From: Jacky <66659162+Perpete@users.noreply.github.com> Date: Thu, 28 Oct 2021 17:58:22 +0200 Subject: [PATCH 07/30] Correction for arrays of more than 2 dimensions When using the type interpretation for arrays of more than 2 dimensions, on deserialization, an error is encountered. There is a problem in the switch case that does not allow adding more than one comma between the brackets of System.xxxx []. View issue #2591 --- Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs index 5e09de1e7..ad7d7a430 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -187,19 +187,30 @@ private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) // loop through the type name and filter out qualified assembly details from nested type names bool writingAssemblyName = false; bool skippingAssemblyDetails = false; + bool DimensionArrayMaybe = false; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': + writingAssemblyName = false; + skippingAssemblyDetails = false; + DimensionArrayMaybe = true; + builder.Append(current); + break; case ']': writingAssemblyName = false; skippingAssemblyDetails = false; + DimensionArrayMaybe = false; builder.Append(current); break; case ',': - if (!writingAssemblyName) + if (DimensionArrayMaybe) + { + builder.Append(current); + } + else if (!writingAssemblyName) { writingAssemblyName = true; builder.Append(current); @@ -210,6 +221,7 @@ private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) } break; default: + DimensionArrayMaybe = false; if (!skippingAssemblyDetails) { builder.Append(current); @@ -1093,4 +1105,4 @@ public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType return Activator.CreateInstance(type); } } -} \ No newline at end of file +} From af6e7b9c13b80c5fef38204a7543e38cc532961d Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Sat, 13 Nov 2021 15:06:40 +1300 Subject: [PATCH 08/30] Refactor type name multidimensional array support and add tests --- .../Serialization/TypeNameHandlingTests.cs | 119 ++++++++++++++++++ .../TestObjects/HasByteArray.cs | 6 + .../Utilities/ReflectionUtils.cs | 10 +- 3 files changed, 130 insertions(+), 5 deletions(-) diff --git a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs index 2b65d0aa1..ccb5543cc 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs @@ -62,6 +62,125 @@ namespace Newtonsoft.Json.Tests.Serialization [TestFixture] public class TypeNameHandlingTests : TestFixtureBase { + [Test] + public void SerializeMultidimensionalByteArrayWithTypeName() + { + string array2dRef = ReflectionUtils.GetTypeName(typeof(byte[,]), TypeNameAssemblyFormatHandling.Simple, null); + string array3dRef = ReflectionUtils.GetTypeName(typeof(byte[,,]), TypeNameAssemblyFormatHandling.Simple, null); + + HasMultidimensionalByteArray o = new HasMultidimensionalByteArray + { + Array2D = new byte[,] { { 1, 2 }, { 2, 4 }, { 3, 6 } }, + Array3D = new byte[,,] { { { 1, 2, 3}, { 4, 5, 6 } } } + }; + + string json = JsonConvert.SerializeObject(o, new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.All, + Formatting = Formatting.Indented + }); + + string expectedJson = @"{ + ""$type"": ""Newtonsoft.Json.Tests.TestObjects.HasMultidimensionalByteArray, Newtonsoft.Json.Tests"", + ""Array2D"": { + ""$type"": """ + array2dRef + @""", + ""$values"": [ + [ + 1, + 2 + ], + [ + 2, + 4 + ], + [ + 3, + 6 + ] + ] + }, + ""Array3D"": { + ""$type"": """ + array3dRef + @""", + ""$values"": [ + [ + [ + 1, + 2, + 3 + ], + [ + 4, + 5, + 6 + ] + ] + ] + } +}"; + + StringAssert.AreEqual(expectedJson, json); + } + + + [Test] + public void DeserializeMultidimensionalByteArrayWithTypeName() + { + string json = @"{ + ""$type"": ""Newtonsoft.Json.Tests.TestObjects.HasMultidimensionalByteArray, Newtonsoft.Json.Tests"", + ""Array2D"": { + ""$type"": ""System.Byte[,], mscorlib"", + ""$values"": [ + [ + 1, + 2 + ], + [ + 2, + 4 + ], + [ + 3, + 6 + ] + ] + }, + ""Array3D"": { + ""$type"": ""System.Byte[,,], mscorlib"", + ""$values"": [ + [ + [ + 1, + 2, + 3 + ], + [ + 4, + 5, + 6 + ] + ] + ] + } +}"; + HasMultidimensionalByteArray value = JsonConvert.DeserializeObject(json, new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.Objects + }); + + Assert.AreEqual(1, value.Array2D[0, 0]); + Assert.AreEqual(2, value.Array2D[0, 1]); + Assert.AreEqual(2, value.Array2D[1, 0]); + Assert.AreEqual(4, value.Array2D[1, 1]); + Assert.AreEqual(3, value.Array2D[2, 0]); + Assert.AreEqual(6, value.Array2D[2, 1]); + + Assert.AreEqual(1, value.Array3D[0, 0, 0]); + Assert.AreEqual(2, value.Array3D[0, 0, 1]); + Assert.AreEqual(3, value.Array3D[0, 0, 2]); + Assert.AreEqual(4, value.Array3D[0, 1, 0]); + Assert.AreEqual(5, value.Array3D[0, 1, 1]); + Assert.AreEqual(6, value.Array3D[0, 1, 2]); + } [Test] public void DeserializeByteArrayWithTypeName() diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/HasByteArray.cs b/Src/Newtonsoft.Json.Tests/TestObjects/HasByteArray.cs index d9fd7d386..102bf70b4 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/HasByteArray.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/HasByteArray.cs @@ -29,4 +29,10 @@ internal class HasByteArray { public byte[] EncryptedPassword { get; set; } } + + internal class HasMultidimensionalByteArray + { + public byte[,] Array2D { get; set; } + public byte[,,] Array3D { get; set; } + } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs index ad7d7a430..fd3cbaea3 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -187,7 +187,7 @@ private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) // loop through the type name and filter out qualified assembly details from nested type names bool writingAssemblyName = false; bool skippingAssemblyDetails = false; - bool DimensionArrayMaybe = false; + bool followBrackets = false; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; @@ -196,17 +196,17 @@ private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) case '[': writingAssemblyName = false; skippingAssemblyDetails = false; - DimensionArrayMaybe = true; + followBrackets = true; builder.Append(current); break; case ']': writingAssemblyName = false; skippingAssemblyDetails = false; - DimensionArrayMaybe = false; + followBrackets = false; builder.Append(current); break; case ',': - if (DimensionArrayMaybe) + if (followBrackets) { builder.Append(current); } @@ -221,7 +221,7 @@ private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) } break; default: - DimensionArrayMaybe = false; + followBrackets = false; if (!skippingAssemblyDetails) { builder.Append(current); From a45ef9f2d99a911f38154ee9d789051608b9f365 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Thu, 2 Dec 2021 15:25:33 +1300 Subject: [PATCH 09/30] Update pipelines image to VS2022 and fix build warnings (#2619) --- Src/Directory.Build.props | 2 +- Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj | 2 ++ azure-pipelines.yml | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Src/Directory.Build.props b/Src/Directory.Build.props index 661350885..bafd1cd9e 100644 --- a/Src/Directory.Build.props +++ b/Src/Directory.Build.props @@ -3,7 +3,7 @@ 4.6.2 0.10.10 4.2.3 - 5.0.3 + 6.0.0 4.3.0 1.0.0 16.3.0 diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj index c074971d6..5b355da4f 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -16,6 +16,8 @@ Full false + + false diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 85e6cfa73..9ff4dd649 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -3,7 +3,7 @@ trigger: - release/* pool: - vmImage: 'windows-2019' + vmImage: 'windows-2022' steps: - task: UseDotNet@2 From 52190a3a3de6ef9a556583cbcb2381073e7197bc Mon Sep 17 00:00:00 2001 From: Jose Perez Rodriguez Date: Sat, 4 Dec 2021 12:00:46 -0800 Subject: [PATCH 10/30] Enabling NuGet package validation (#2618) --- .../CompatibilitySuppressions.xml | 104 ++++++++++++++++++ Src/Newtonsoft.Json/Newtonsoft.Json.csproj | 7 ++ 2 files changed, 111 insertions(+) create mode 100644 Src/Newtonsoft.Json/CompatibilitySuppressions.xml diff --git a/Src/Newtonsoft.Json/CompatibilitySuppressions.xml b/Src/Newtonsoft.Json/CompatibilitySuppressions.xml new file mode 100644 index 000000000..64d04acc5 --- /dev/null +++ b/Src/Newtonsoft.Json/CompatibilitySuppressions.xml @@ -0,0 +1,104 @@ + + + + + CP0001 + T:Newtonsoft.Json.Serialization.Func`1 + lib/net20/Newtonsoft.Json.dll + lib/net35/Newtonsoft.Json.dll + + + CP0001 + T:Newtonsoft.Json.Serialization.Func`2 + lib/net20/Newtonsoft.Json.dll + lib/net35/Newtonsoft.Json.dll + + + CP0001 + T:Newtonsoft.Json.Serialization.Func`3 + lib/net20/Newtonsoft.Json.dll + lib/net35/Newtonsoft.Json.dll + + + CP0001 + T:Newtonsoft.Json.Serialization.Func`4 + lib/net20/Newtonsoft.Json.dll + lib/net35/Newtonsoft.Json.dll + + + CP0001 + T:Newtonsoft.Json.Serialization.Func`5 + lib/net20/Newtonsoft.Json.dll + lib/net35/Newtonsoft.Json.dll + + + CP0001 + T:Newtonsoft.Json.Serialization.Action + lib/net20/Newtonsoft.Json.dll + lib/net35/Newtonsoft.Json.dll + + + CP0001 + T:Newtonsoft.Json.Serialization.Action`2 + lib/net20/Newtonsoft.Json.dll + lib/net35/Newtonsoft.Json.dll + + + CP0001 + T:Newtonsoft.Json.Serialization.Action`3 + lib/net20/Newtonsoft.Json.dll + lib/net35/Newtonsoft.Json.dll + + + CP0001 + T:Newtonsoft.Json.Serialization.Action`4 + lib/net20/Newtonsoft.Json.dll + lib/net35/Newtonsoft.Json.dll + + + + CP0001 + T:System.Runtime.Serialization.Formatters.FormatterAssemblyStyle + lib/netstandard1.3/Newtonsoft.Json.dll + lib/netstandard2.0/Newtonsoft.Json.dll + + + CP0001 + T:Newtonsoft.Json.SerializationBinder + lib/netstandard1.3/Newtonsoft.Json.dll + lib/netstandard2.0/Newtonsoft.Json.dll + + + CP0001 + T:Newtonsoft.Json.TraceLevel + lib/netstandard1.3/Newtonsoft.Json.dll + lib/netstandard2.0/Newtonsoft.Json.dll + + + + CP0007 + T:Newtonsoft.Json.Serialization.DefaultSerializationBinder + lib/netstandard1.3/Newtonsoft.Json.dll + lib/netstandard2.0/Newtonsoft.Json.dll + + + + CP0002 + M:Newtonsoft.Json.Serialization.ITraceWriter.Trace(Newtonsoft.Json.TraceLevel,System.String,System.Exception) + lib/netstandard1.3/Newtonsoft.Json.dll + lib/netstandard2.0/Newtonsoft.Json.dll + + + CP0002 + M:Newtonsoft.Json.Serialization.MemoryTraceWriter.Trace(Newtonsoft.Json.TraceLevel,System.String,System.Exception) + lib/netstandard1.3/Newtonsoft.Json.dll + lib/netstandard2.0/Newtonsoft.Json.dll + + + + CP0006 + M:Newtonsoft.Json.Serialization.ITraceWriter.Trace(System.Diagnostics.TraceLevel,System.String,System.Exception) + lib/netstandard1.3/Newtonsoft.Json.dll + lib/netstandard2.0/Newtonsoft.Json.dll + + \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index 6f4bea65f..fd834d77a 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -33,6 +33,13 @@ snupkg Newtonsoft.Json.ruleset true + + true + 13.0.1 + + $(NoWarn);CP0003 From 197c6db94a19eaca018debac6e2d07e2ba22ba75 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Sun, 15 May 2022 21:40:07 +0800 Subject: [PATCH 11/30] Update tests to use .NET 6 (#2674) --- Build/build.ps1 | 2 +- .../Newtonsoft.Json.TestConsole.csproj | 2 +- Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj | 6 +++--- .../Utilities/ExpressionReflectionDelegateFactoryTests.cs | 3 ++- Src/global.json | 2 +- 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Build/build.ps1 b/Build/build.ps1 index 718de33c1..7491dc6ff 100644 --- a/Build/build.ps1 +++ b/Build/build.ps1 @@ -32,7 +32,7 @@ $nunitConsolePath = "$buildDir\Temp\NUnit.ConsoleRunner.$nunitConsoleVersion" $builds = @( - @{Framework = "netstandard2.0"; TestsFunction = "NetCliTests"; TestFramework = "net5.0"; Enabled=$true}, + @{Framework = "netstandard2.0"; TestsFunction = "NetCliTests"; TestFramework = "net6.0"; Enabled=$true}, @{Framework = "netstandard1.3"; TestsFunction = "NetCliTests"; TestFramework = "netcoreapp3.1"; Enabled=$true}, @{Framework = "netstandard1.0"; TestsFunction = "NetCliTests"; TestFramework = "netcoreapp2.1"; Enabled=$true}, @{Framework = "net45"; TestsFunction = "NUnitTests"; TestFramework = "net46"; NUnitFramework="net-4.0"; Enabled=$true}, diff --git a/Src/Newtonsoft.Json.TestConsole/Newtonsoft.Json.TestConsole.csproj b/Src/Newtonsoft.Json.TestConsole/Newtonsoft.Json.TestConsole.csproj index 5959077a6..b8a43257f 100644 --- a/Src/Newtonsoft.Json.TestConsole/Newtonsoft.Json.TestConsole.csproj +++ b/Src/Newtonsoft.Json.TestConsole/Newtonsoft.Json.TestConsole.csproj @@ -1,7 +1,7 @@  Exe - net46;net5.0 + net46;net6.0 latest Newtonsoft.Json.TestConsole Newtonsoft.Json.TestConsole diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj index 5b355da4f..250b9b661 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -1,6 +1,6 @@  - net46;net40;net35;net20;net5.0;netcoreapp3.1;netcoreapp2.1 + net46;net40;net35;net20;net6.0;netcoreapp3.1;netcoreapp2.1 $(TestFrameworks) 9.0 1.0 @@ -109,7 +109,7 @@ NET20;$(AdditionalConstants) - + @@ -124,7 +124,7 @@ - + Json.NET Tests .NET Standard 2.0 .NETStandard,Version=v2.0 NETSTANDARD2_0;DNXCORE50;PORTABLE;HAVE_BENCHMARKS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) diff --git a/Src/Newtonsoft.Json.Tests/Utilities/ExpressionReflectionDelegateFactoryTests.cs b/Src/Newtonsoft.Json.Tests/Utilities/ExpressionReflectionDelegateFactoryTests.cs index ef6e561d9..9488ab9ee 100644 --- a/Src/Newtonsoft.Json.Tests/Utilities/ExpressionReflectionDelegateFactoryTests.cs +++ b/Src/Newtonsoft.Json.Tests/Utilities/ExpressionReflectionDelegateFactoryTests.cs @@ -145,7 +145,8 @@ public void DefaultConstructor_Abstract() }, new[] { "Cannot create an abstract class.", - "Cannot create an abstract class 'System.Type'." // mono + "Cannot create an abstract class 'System.Type'.", // mono + "Cannot dynamically create an instance of type 'System.Type'. Reason: Cannot create an abstract class." // net60 }); } diff --git a/Src/global.json b/Src/global.json index 047020849..19c87f2a5 100644 --- a/Src/global.json +++ b/Src/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "6.0.100" + "version": "6.0.300" } } From 13717cfc452ee9c1ea0b4fc368b8e9922d562028 Mon Sep 17 00:00:00 2001 From: Marc Gravell Date: Sun, 15 May 2022 15:08:18 +0100 Subject: [PATCH 12/30] implement box avoidance (#2639) Co-authored-by: Marc Gravell Co-authored-by: James Newton-King --- Src/Newtonsoft.Json.Tests/Issues/Issue2484.cs | 2 +- Src/Newtonsoft.Json.Tests/Issues/Issue2492.cs | 2 +- Src/Newtonsoft.Json.Tests/Issues/Issue2504.cs | 2 +- Src/Newtonsoft.Json.Tests/Issues/Issue2529.cs | 2 +- Src/Newtonsoft.Json.Tests/Issues/Issue2638.cs | 129 ++++++++++++++++++ .../Newtonsoft.Json.Tests.csproj | 2 +- Src/Newtonsoft.Json/JsonTextReader.cs | 40 +++--- Src/Newtonsoft.Json/Linq/JTokenWriter.cs | 56 ++++---- Src/Newtonsoft.Json/Linq/JValue.cs | 8 +- .../Utilities/BoxedPrimitives.cs | 116 ++++++++++++++++ 10 files changed, 302 insertions(+), 57 deletions(-) create mode 100644 Src/Newtonsoft.Json.Tests/Issues/Issue2638.cs create mode 100644 Src/Newtonsoft.Json/Utilities/BoxedPrimitives.cs diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2484.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2484.cs index baa70f32f..d779bb184 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue2484.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2484.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if (NET45 || NET50) +#if (NET45 || NET5_0_OR_GREATER) #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2492.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2492.cs index 70268abfc..34146a665 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue2492.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2492.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if (NET45 || NET50) +#if (NET45 || NET5_0_OR_GREATER) #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2504.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2504.cs index 4363a9112..9ff3be6e7 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue2504.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2504.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if (NET45 || NET50) +#if (NET45 || NET5_0_OR_GREATER) #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2529.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2529.cs index 5d7cb7b9d..8406bfc0c 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue2529.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2529.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if (NET45 || NET50) +#if (NET45 || NET5_0_OR_GREATER) #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2638.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2638.cs new file mode 100644 index 000000000..c32fe4c6c --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2638.cs @@ -0,0 +1,129 @@ +#region License +// Copyright (c) 2022 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using Newtonsoft.Json.Linq; +using System.Globalization; +using Newtonsoft.Json.Tests.Documentation.Samples.Linq; + +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif + +namespace Newtonsoft.Json.Tests.Issues +{ + [TestFixture] + public class Issue2638 + { + [Test] + public void DeserilizeUsesSharedBooleans() + { + Test(true); + Test(false); + + static void Test(bool value) + { + var obj = (JObject)JToken.Parse(@"{""x"": XXX, ""y"": XXX}".Replace("XXX", value ? "true" : "false")); + var x = ((JValue)obj["x"]).Value; + var y = ((JValue)obj["y"]).Value; + + Assert.AreEqual(value, (bool)x); + Assert.AreEqual(value, (bool)y); + Assert.AreSame(x, y); + } + } + + [Test] + public void DeserilizeUsesSharedDoubleZeros() + { + Test(0, true); + Test(double.NaN, true); + Test(double.NegativeInfinity, true); + Test(double.PositiveInfinity, true); + Test(1, false); + Test(42.42, false); + + static void Test(double value, bool expectSame) + { + var obj = (JObject)JToken.Parse(@"{""x"": XXX, ""y"": XXX}".Replace("XXX", value.ToString("0.0###", CultureInfo.InvariantCulture))); + var x = ((JValue)obj["x"]).Value; + var y = ((JValue)obj["y"]).Value; + + Assert.AreEqual(value, (double)x); + Assert.AreEqual(value, (double)y); + if (expectSame) + { + Assert.AreSame(x, y); + } + else + { + Assert.AreNotSame(x, y); + } + var unboxed = (double)x; + Assert.AreEqual(double.IsNaN(value), double.IsNaN(unboxed)); + Assert.AreEqual(double.IsPositiveInfinity(value), double.IsPositiveInfinity(unboxed)); + Assert.AreEqual(double.IsNegativeInfinity(value), double.IsNegativeInfinity(unboxed)); + } + } + + [Test] + public void DeserilizeUsesSharedSmallInt64() + { + Test(-2, false); + Test(-1, true); + Test(0, true); + Test(1, true); + Test(2, true); + Test(3, true); + Test(4, true); + Test(5, true); + Test(6, true); + Test(7, true); + Test(8, true); + Test(9, false); + + static void Test(long value, bool expectSame) + { + var obj = (JObject)JToken.Parse(@"{""x"": XXX, ""y"": XXX}".Replace("XXX", value.ToString(CultureInfo.InvariantCulture))); + var x = ((JValue)obj["x"]).Value; + var y = ((JValue)obj["y"]).Value; + + Assert.AreEqual(value, (long)x); + Assert.AreEqual(value, (long)y); + if (expectSame) + { + Assert.AreSame(x, y); + } + else + { + Assert.AreNotSame(x, y); + } + } + } + } +} diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj index 250b9b661..f1166b1a2 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -13,7 +13,7 @@ Newtonsoft.Json.Tests false - Full + Full false diff --git a/Src/Newtonsoft.Json/JsonTextReader.cs b/Src/Newtonsoft.Json/JsonTextReader.cs index 0ef5b0e55..6b107b0e0 100644 --- a/Src/Newtonsoft.Json/JsonTextReader.cs +++ b/Src/Newtonsoft.Json/JsonTextReader.cs @@ -841,7 +841,7 @@ private JsonReaderException CreateUnexpectedCharacterException(char c) { throw CreateUnexpectedCharacterException(_chars[_charPos]); } - SetToken(JsonToken.Boolean, isTrue); + SetToken(JsonToken.Boolean, BoxedPrimitives.Get(isTrue)); return isTrue; case '/': ParseComment(false); @@ -2030,7 +2030,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit if (singleDigit) { // digit char values start at 48 - numberValue = firstChar - 48; + numberValue = BoxedPrimitives.Get(firstChar - 48); } else if (nonBase10) { @@ -2040,7 +2040,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit { int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt32(number, 16) : Convert.ToInt32(number, 8); - numberValue = integer; + numberValue = BoxedPrimitives.Get(integer); } catch (Exception ex) { @@ -2052,7 +2052,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit ParseResult parseResult = ConvertUtils.Int32TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out int value); if (parseResult == ParseResult.Success) { - numberValue = value; + numberValue = BoxedPrimitives.Get(value); } else if (parseResult == ParseResult.Overflow) { @@ -2072,7 +2072,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit if (singleDigit) { // digit char values start at 48 - numberValue = (decimal)firstChar - 48; + numberValue = BoxedPrimitives.Get((decimal)firstChar - 48); } else if (nonBase10) { @@ -2083,7 +2083,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit // decimal.Parse doesn't support parsing hexadecimal values long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); - numberValue = Convert.ToDecimal(integer); + numberValue = BoxedPrimitives.Get(Convert.ToDecimal(integer)); } catch (Exception ex) { @@ -2095,7 +2095,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit ParseResult parseResult = ConvertUtils.DecimalTryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out decimal value); if (parseResult == ParseResult.Success) { - numberValue = value; + numberValue = BoxedPrimitives.Get(value); } else { @@ -2111,7 +2111,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit if (singleDigit) { // digit char values start at 48 - numberValue = (double)firstChar - 48; + numberValue = BoxedPrimitives.Get((double)firstChar - 48); } else if (nonBase10) { @@ -2122,7 +2122,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit // double.Parse doesn't support parsing hexadecimal values long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); - numberValue = Convert.ToDouble(integer); + numberValue = BoxedPrimitives.Get(Convert.ToDouble(integer)); } catch (Exception ex) { @@ -2135,7 +2135,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit if (double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out double value)) { - numberValue = value; + numberValue = BoxedPrimitives.Get(value); } else { @@ -2152,7 +2152,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit if (singleDigit) { // digit char values start at 48 - numberValue = (long)firstChar - 48; + numberValue = BoxedPrimitives.Get((long)firstChar - 48); numberType = JsonToken.Integer; } else if (nonBase10) @@ -2161,7 +2161,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit try { - numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8); + numberValue = BoxedPrimitives.Get(number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8)); } catch (Exception ex) { @@ -2175,7 +2175,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out long value); if (parseResult == ParseResult.Success) { - numberValue = value; + numberValue = BoxedPrimitives.Get(value); numberType = JsonToken.Integer; } else if (parseResult == ParseResult.Overflow) @@ -2201,7 +2201,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit parseResult = ConvertUtils.DecimalTryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out decimal d); if (parseResult == ParseResult.Success) { - numberValue = d; + numberValue = BoxedPrimitives.Get(d); } else { @@ -2214,7 +2214,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit if (double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out double d)) { - numberValue = d; + numberValue = BoxedPrimitives.Get(d); } else { @@ -2455,7 +2455,7 @@ private void ParseTrue() // or the text ends if (MatchValueWithTrailingSeparator(JsonConvert.True)) { - SetToken(JsonToken.Boolean, true); + SetToken(JsonToken.Boolean, BoxedPrimitives.BooleanTrue); } else { @@ -2491,7 +2491,7 @@ private void ParseFalse() { if (MatchValueWithTrailingSeparator(JsonConvert.False)) { - SetToken(JsonToken.Boolean, false); + SetToken(JsonToken.Boolean, BoxedPrimitives.BooleanFalse); } else { @@ -2514,7 +2514,7 @@ private object ParseNumberNegativeInfinity(ReadType readType, bool matched) case ReadType.ReadAsDouble: if (_floatParseHandling == FloatParseHandling.Double) { - SetToken(JsonToken.Float, double.NegativeInfinity); + SetToken(JsonToken.Float, BoxedPrimitives.DoubleNegativeInfinity); return double.NegativeInfinity; } break; @@ -2543,7 +2543,7 @@ private object ParseNumberPositiveInfinity(ReadType readType, bool matched) case ReadType.ReadAsDouble: if (_floatParseHandling == FloatParseHandling.Double) { - SetToken(JsonToken.Float, double.PositiveInfinity); + SetToken(JsonToken.Float, BoxedPrimitives.DoublePositiveInfinity); return double.PositiveInfinity; } break; @@ -2573,7 +2573,7 @@ private object ParseNumberNaN(ReadType readType, bool matched) case ReadType.ReadAsDouble: if (_floatParseHandling == FloatParseHandling.Double) { - SetToken(JsonToken.Float, double.NaN); + SetToken(JsonToken.Float, BoxedPrimitives.DoubleNaN); return double.NaN; } break; diff --git a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs index 9e281c608..344ae8343 100644 --- a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs +++ b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs @@ -187,12 +187,12 @@ public override void WritePropertyName(string name) base.WritePropertyName(name); } - private void AddValue(object? value, JsonToken token) + private void AddRawValue(object? value, JTokenType type, JsonToken token) { - AddValue(new JValue(value), token); + AddJValue(new JValue(value, type), token); } - internal void AddValue(JValue? value, JsonToken token) + internal void AddJValue(JValue? value, JsonToken token) { if (_parent != null) { @@ -228,7 +228,7 @@ public override void WriteValue(object? value) if (value is BigInteger) { InternalWriteValue(JsonToken.Integer); - AddValue(value, JsonToken.Integer); + AddRawValue(value, JTokenType.Integer, JsonToken.Integer); } else #endif @@ -243,7 +243,7 @@ public override void WriteValue(object? value) public override void WriteNull() { base.WriteNull(); - AddValue(null, JsonToken.Null); + AddJValue(JValue.CreateNull(), JsonToken.Null); } /// @@ -252,7 +252,7 @@ public override void WriteNull() public override void WriteUndefined() { base.WriteUndefined(); - AddValue(null, JsonToken.Undefined); + AddJValue(JValue.CreateUndefined(), JsonToken.Undefined); } /// @@ -262,7 +262,7 @@ public override void WriteUndefined() public override void WriteRaw(string? json) { base.WriteRaw(json); - AddValue(new JRaw(json), JsonToken.Raw); + AddJValue(new JRaw(json), JsonToken.Raw); } /// @@ -272,7 +272,7 @@ public override void WriteRaw(string? json) public override void WriteComment(string? text) { base.WriteComment(text); - AddValue(JValue.CreateComment(text), JsonToken.Comment); + AddJValue(JValue.CreateComment(text), JsonToken.Comment); } /// @@ -282,7 +282,7 @@ public override void WriteComment(string? text) public override void WriteValue(string? value) { base.WriteValue(value); - AddValue(value, JsonToken.String); + AddJValue(new JValue(value), JsonToken.String); } /// @@ -292,7 +292,7 @@ public override void WriteValue(string? value) public override void WriteValue(int value) { base.WriteValue(value); - AddValue(value, JsonToken.Integer); + AddRawValue(value, JTokenType.Integer, JsonToken.Integer); } /// @@ -303,7 +303,7 @@ public override void WriteValue(int value) public override void WriteValue(uint value) { base.WriteValue(value); - AddValue(value, JsonToken.Integer); + AddRawValue(value, JTokenType.Integer, JsonToken.Integer); } /// @@ -313,7 +313,7 @@ public override void WriteValue(uint value) public override void WriteValue(long value) { base.WriteValue(value); - AddValue(value, JsonToken.Integer); + AddJValue(new JValue(value), JsonToken.Integer); } /// @@ -324,7 +324,7 @@ public override void WriteValue(long value) public override void WriteValue(ulong value) { base.WriteValue(value); - AddValue(value, JsonToken.Integer); + AddJValue(new JValue(value), JsonToken.Integer); } /// @@ -334,7 +334,7 @@ public override void WriteValue(ulong value) public override void WriteValue(float value) { base.WriteValue(value); - AddValue(value, JsonToken.Float); + AddJValue(new JValue(value), JsonToken.Float); } /// @@ -344,7 +344,7 @@ public override void WriteValue(float value) public override void WriteValue(double value) { base.WriteValue(value); - AddValue(value, JsonToken.Float); + AddJValue(new JValue(value), JsonToken.Float); } /// @@ -354,7 +354,7 @@ public override void WriteValue(double value) public override void WriteValue(bool value) { base.WriteValue(value); - AddValue(value, JsonToken.Boolean); + AddJValue(new JValue(value), JsonToken.Boolean); } /// @@ -364,7 +364,7 @@ public override void WriteValue(bool value) public override void WriteValue(short value) { base.WriteValue(value); - AddValue(value, JsonToken.Integer); + AddRawValue(value, JTokenType.Integer, JsonToken.Integer); } /// @@ -375,7 +375,7 @@ public override void WriteValue(short value) public override void WriteValue(ushort value) { base.WriteValue(value); - AddValue(value, JsonToken.Integer); + AddRawValue(value, JTokenType.Integer, JsonToken.Integer); } /// @@ -391,7 +391,7 @@ public override void WriteValue(char value) #else s = value.ToString(); #endif - AddValue(s, JsonToken.String); + AddJValue(new JValue(s), JsonToken.String); } /// @@ -401,7 +401,7 @@ public override void WriteValue(char value) public override void WriteValue(byte value) { base.WriteValue(value); - AddValue(value, JsonToken.Integer); + AddRawValue(value, JTokenType.Integer, JsonToken.Integer); } /// @@ -412,7 +412,7 @@ public override void WriteValue(byte value) public override void WriteValue(sbyte value) { base.WriteValue(value); - AddValue(value, JsonToken.Integer); + AddRawValue(value, JTokenType.Integer, JsonToken.Integer); } /// @@ -422,7 +422,7 @@ public override void WriteValue(sbyte value) public override void WriteValue(decimal value) { base.WriteValue(value); - AddValue(value, JsonToken.Float); + AddJValue(new JValue(value), JsonToken.Float); } /// @@ -433,7 +433,7 @@ public override void WriteValue(DateTime value) { base.WriteValue(value); value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling); - AddValue(value, JsonToken.Date); + AddJValue(new JValue(value), JsonToken.Date); } #if HAVE_DATE_TIME_OFFSET @@ -444,7 +444,7 @@ public override void WriteValue(DateTime value) public override void WriteValue(DateTimeOffset value) { base.WriteValue(value); - AddValue(value, JsonToken.Date); + AddJValue(new JValue(value), JsonToken.Date); } #endif @@ -455,7 +455,7 @@ public override void WriteValue(DateTimeOffset value) public override void WriteValue(byte[]? value) { base.WriteValue(value); - AddValue(value, JsonToken.Bytes); + AddJValue(new JValue(value, JTokenType.Bytes), JsonToken.Bytes); } /// @@ -465,7 +465,7 @@ public override void WriteValue(byte[]? value) public override void WriteValue(TimeSpan value) { base.WriteValue(value); - AddValue(value, JsonToken.String); + AddJValue(new JValue(value), JsonToken.String); } /// @@ -475,7 +475,7 @@ public override void WriteValue(TimeSpan value) public override void WriteValue(Guid value) { base.WriteValue(value); - AddValue(value, JsonToken.String); + AddJValue(new JValue(value), JsonToken.String); } /// @@ -485,7 +485,7 @@ public override void WriteValue(Guid value) public override void WriteValue(Uri? value) { base.WriteValue(value); - AddValue(value, JsonToken.String); + AddJValue(new JValue(value), JsonToken.String); } #endregion diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs index 27d5de882..86ea4dfe6 100644 --- a/Src/Newtonsoft.Json/Linq/JValue.cs +++ b/Src/Newtonsoft.Json/Linq/JValue.cs @@ -72,7 +72,7 @@ public JValue(JValue other) /// /// The value. public JValue(long value) - : this(value, JTokenType.Integer) + : this(BoxedPrimitives.Get(value), JTokenType.Integer) { } @@ -81,7 +81,7 @@ public JValue(long value) /// /// The value. public JValue(decimal value) - : this(value, JTokenType.Float) + : this(BoxedPrimitives.Get(value), JTokenType.Float) { } @@ -109,7 +109,7 @@ public JValue(ulong value) /// /// The value. public JValue(double value) - : this(value, JTokenType.Float) + : this(BoxedPrimitives.Get(value), JTokenType.Float) { } @@ -147,7 +147,7 @@ public JValue(DateTimeOffset value) /// /// The value. public JValue(bool value) - : this(value, JTokenType.Boolean) + : this(BoxedPrimitives.Get(value), JTokenType.Boolean) { } diff --git a/Src/Newtonsoft.Json/Utilities/BoxedPrimitives.cs b/Src/Newtonsoft.Json/Utilities/BoxedPrimitives.cs new file mode 100644 index 000000000..e6fb4f2de --- /dev/null +++ b/Src/Newtonsoft.Json/Utilities/BoxedPrimitives.cs @@ -0,0 +1,116 @@ +#region License +// Copyright (c) 2022 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +namespace Newtonsoft.Json.Utilities +{ + internal static class BoxedPrimitives + { + internal static object Get(bool value) => value ? BooleanTrue : BooleanFalse; + + internal static readonly object BooleanTrue = true; + internal static readonly object BooleanFalse = false; + + internal static object Get(int value) => value switch + { + -1 => Int32_M1, + 0 => Int32_0, + 1 => Int32_1, + 2 => Int32_2, + 3 => Int32_3, + 4 => Int32_4, + 5 => Int32_5, + 6 => Int32_6, + 7 => Int32_7, + 8 => Int32_8, + _ => value, + }; + + // integers tend to be weighted towards a handful of low numbers; we could argue + // for days over the "correct" range to have special handling, but I'm arbitrarily + // mirroring the same decision as the IL opcodes, which has M1 thru 8 + internal static readonly object Int32_M1 = -1; + internal static readonly object Int32_0 = 0; + internal static readonly object Int32_1 = 1; + internal static readonly object Int32_2 = 2; + internal static readonly object Int32_3 = 3; + internal static readonly object Int32_4 = 4; + internal static readonly object Int32_5 = 5; + internal static readonly object Int32_6 = 6; + internal static readonly object Int32_7 = 7; + internal static readonly object Int32_8 = 8; + + internal static object Get(long value) => value switch + { + -1 => Int64_M1, + 0 => Int64_0, + 1 => Int64_1, + 2 => Int64_2, + 3 => Int64_3, + 4 => Int64_4, + 5 => Int64_5, + 6 => Int64_6, + 7 => Int64_7, + 8 => Int64_8, + _ => value, + }; + + internal static readonly object Int64_M1 = -1L; + internal static readonly object Int64_0 = 0L; + internal static readonly object Int64_1 = 1L; + internal static readonly object Int64_2 = 2L; + internal static readonly object Int64_3 = 3L; + internal static readonly object Int64_4 = 4L; + internal static readonly object Int64_5 = 5L; + internal static readonly object Int64_6 = 6L; + internal static readonly object Int64_7 = 7L; + internal static readonly object Int64_8 = 8L; + + internal static object Get(decimal value) => value == decimal.Zero ? DecimalZero : value; + + private static readonly object DecimalZero = decimal.Zero; + + internal static object Get(double value) + { + if (value == 0.0d) + { + return DoubleZero; + } + if (double.IsInfinity(value)) + { + return double.IsPositiveInfinity(value) ? DoublePositiveInfinity : DoubleNegativeInfinity; + } + if (double.IsNaN(value)) + { + return DoubleNaN; + } + return value; + } + + internal static readonly object DoubleNaN = double.NaN; + internal static readonly object DoublePositiveInfinity = double.PositiveInfinity; + internal static readonly object DoubleNegativeInfinity = double.NegativeInfinity; + internal static readonly object DoubleZero = (double)0; + } +} From 7f78562d4496d6881e3f60504473127656b98554 Mon Sep 17 00:00:00 2001 From: MaxKot Date: Sun, 15 May 2022 17:43:37 +0300 Subject: [PATCH 13/30] Add support to pre-epoch Unix time (#2614) Co-authored-by: Max A. Kiselev Co-authored-by: James Newton-King --- .../Converters/UnixDateTimeConverterTests.cs | 87 +++++++++++++++++++ .../Converters/UnixDateTimeConverter.cs | 35 +++++++- 2 files changed, 120 insertions(+), 2 deletions(-) diff --git a/Src/Newtonsoft.Json.Tests/Converters/UnixDateTimeConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/UnixDateTimeConverterTests.cs index 638c74844..ed8ee1f9b 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/UnixDateTimeConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/UnixDateTimeConverterTests.cs @@ -25,6 +25,7 @@ using System; using System.Collections.Generic; +using System.Globalization; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; @@ -71,6 +72,17 @@ public void SerializeInvalidDate() ); } + [Test] + public void SerializeDateBeforeEpoch() + { + DateTime date = new DateTime(1964, 2, 7); + long dateSeconds = (long)(date.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds; + + string result = JsonConvert.SerializeObject(date, new UnixDateTimeConverter { AllowPreEpoch = true }); + + Assert.AreEqual(dateSeconds.ToString(CultureInfo.InvariantCulture), result); + } + [Test] public void WriteJsonInvalidType() { @@ -159,6 +171,19 @@ public void DeserializeInvalidStringToDateTimeOffset() "Cannot convert invalid value to System.DateTimeOffset. Path '', line 1, position 5." ); } + + [Test] + public void DeserializeDateTimeOffsetBeforeEpoch() + { + UnixDateTimeConverter converter = new UnixDateTimeConverter(true); + DateTimeOffset d = new DateTimeOffset(1969, 2, 1, 20, 6, 18, TimeSpan.Zero); + + string json = JsonConvert.SerializeObject(d, converter); + + DateTimeOffset result = JsonConvert.DeserializeObject(json, converter); + + Assert.AreEqual(new DateTimeOffset(1969, 2, 1, 20, 6, 18, TimeSpan.Zero), result); + } #endif [Test] @@ -186,6 +211,14 @@ public void DeserializeInvalidValue() ); } + [Test] + public void DeserializeNegativeIntegerToDateTimeBeforeEpoch() + { + DateTime result = JsonConvert.DeserializeObject("-1514840476", new UnixDateTimeConverter(true)); + + Assert.AreEqual(new DateTime(1921, 12, 31, 02, 58, 44, DateTimeKind.Utc), result); + } + [Test] public void DeserializeInvalidValueType() { @@ -263,6 +296,49 @@ public void ConverterObject() Assert.IsNull(obj2.Object2); Assert.AreEqual(new DateTime(2018, 1, 1, 21, 1, 16, DateTimeKind.Utc), obj2.ObjectNotHandled); } + +#if !NET20 + [Test] + public void ConverterObjectWithDatesBeforeEpoch() + { + PreEpochUnixConverterObject obj1 = new PreEpochUnixConverterObject + { + Date1 = new DateTime(1969, 1, 1, 0, 0, 3, DateTimeKind.Utc), + Date2 = new DateTimeOffset(1969, 1, 1, 0, 0, 3, TimeSpan.Zero) + }; + + string json = JsonConvert.SerializeObject(obj1, Formatting.Indented); + StringAssert.AreEqual(@"{ + ""Date1"": -31535997, + ""Date2"": -31535997 +}", json); + + PreEpochUnixConverterObject obj2 = JsonConvert.DeserializeObject(json); + Assert.IsNotNull(obj2); + + Assert.AreEqual(new DateTime(1969, 1, 1, 0, 0, 3, DateTimeKind.Utc), obj2.Date1); + Assert.AreEqual(new DateTimeOffset(1969, 1, 1, 0, 0, 3, TimeSpan.Zero), obj2.Date2); + } +#else + [Test] + public void ConverterObjectWithDatesBeforeEpoch() + { + PreEpochUnixConverterObject obj1 = new PreEpochUnixConverterObject + { + Date1 = new DateTime(1969, 1, 1, 0, 0, 3, DateTimeKind.Utc) + }; + + string json = JsonConvert.SerializeObject(obj1, Formatting.Indented); + StringAssert.AreEqual(@"{ + ""Date1"": -31535997 +}", json); + + PreEpochUnixConverterObject obj2 = JsonConvert.DeserializeObject(json); + Assert.IsNotNull(obj2); + + Assert.AreEqual(new DateTime(1969, 1, 1, 0, 0, 3, DateTimeKind.Utc), obj2.Date1); + } +#endif } [JsonArray(ItemConverterType = typeof(UnixDateTimeConverter))] @@ -281,4 +357,15 @@ public class UnixConverterObject [JsonConverter(typeof(UnixDateTimeConverter))] public object ObjectNotHandled { get; set; } } + + public class PreEpochUnixConverterObject + { + [JsonConverter(typeof(UnixDateTimeConverter), true)] + public DateTime Date1 { get; set; } + +#if !NET20 + [JsonConverter (typeof(UnixDateTimeConverter), true)] + public DateTimeOffset Date2 { get; set; } +#endif + } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs index d80be6edd..a211813dc 100644 --- a/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs @@ -36,6 +36,37 @@ public class UnixDateTimeConverter : DateTimeConverterBase { internal static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + /// + /// Gets or sets a value indicating whether the dates before Unix epoch + /// should converted to and from JSON. + /// + /// + /// true to allow converting dates before Unix epoch to and from JSON; + /// false to throw an exception when a date being converted to or from JSON + /// occurred before Unix epoch. The default value is false. + /// + public bool AllowPreEpoch { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public UnixDateTimeConverter() : this(false) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// true to allow converting dates before Unix epoch to and from JSON; + /// false to throw an exception when a date being converted to or from JSON + /// occurred before Unix epoch. The default value is false. + /// + public UnixDateTimeConverter(bool allowPreEpoch) + { + AllowPreEpoch = allowPreEpoch; + } + /// /// Writes the JSON representation of the object. /// @@ -61,7 +92,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer throw new JsonSerializationException("Expected date object value."); } - if (seconds < 0) + if (!AllowPreEpoch && seconds < 0) { throw new JsonSerializationException("Cannot convert date value that is before Unix epoch of 00:00:00 UTC on 1 January 1970."); } @@ -108,7 +139,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer or String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } - if (seconds >= 0) + if (AllowPreEpoch || seconds >= 0) { DateTime d = UnixEpoch.AddSeconds(seconds); From 71be691f920e03aa6efaf52ccccde2eeecbe4fed Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Mon, 16 May 2022 09:34:38 +0800 Subject: [PATCH 14/30] Add copy constructor to JsonSerializerSettings (#2676) Co-authored-by: Matthew Steeples --- .../Serialization/JsonSerializerTest.cs | 123 ++++++++++++++++++ Src/Newtonsoft.Json/JsonSerializerSettings.cs | 45 +++++++ 2 files changed, 168 insertions(+) diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs index 6ca78fb3e..b0d3a18a6 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs @@ -48,6 +48,7 @@ using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; +using TestCase = Xunit.InlineDataAttribute; #else using NUnit.Framework; #endif @@ -8076,6 +8077,128 @@ public void SetMaxDepth_MaxValueDepthNotExceeded() Assert.AreEqual(150, depth); } +#if DNXCORE50 + [Theory] +#endif + [TestCase(true)] + [TestCase(false)] + public void ShallowCopy_CopyAllProperties(bool specifyDateFormatString) + { + var propertyNames = typeof(JsonSerializerSettings).GetProperties().Select(property => property.Name).ToList(); + + var settings = new JsonSerializerSettings(); + if (specifyDateFormatString) + { + settings.DateFormatString = "yyyy"; + } + + var clone = new JsonSerializerSettings(settings); + + Assert.AreEqual(settings.DateFormatString, clone.DateFormatString); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.DateFormatString))); + + Assert.AreEqual(settings.DateFormatHandling, clone.DateFormatHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.DateFormatHandling))); + + Assert.AreEqual(settings.ReferenceLoopHandling, clone.ReferenceLoopHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.ReferenceLoopHandling))); + + Assert.AreEqual(settings.MissingMemberHandling, clone.MissingMemberHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.MissingMemberHandling))); + + Assert.AreEqual(settings.ObjectCreationHandling, clone.ObjectCreationHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.ObjectCreationHandling))); + + Assert.AreEqual(settings.NullValueHandling, clone.NullValueHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.NullValueHandling))); + + Assert.AreEqual(settings.DefaultValueHandling, clone.DefaultValueHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.DefaultValueHandling))); + + Assert.AreEqual(settings.Converters, clone.Converters); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.Converters))); + + Assert.AreEqual(settings.PreserveReferencesHandling, clone.PreserveReferencesHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.PreserveReferencesHandling))); + + Assert.AreEqual(settings.TypeNameHandling, clone.TypeNameHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.TypeNameHandling))); + + Assert.AreEqual(settings.MetadataPropertyHandling, clone.MetadataPropertyHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.MetadataPropertyHandling))); + +#pragma warning disable CS0618 // Type or member is obsolete + Assert.AreEqual(settings.TypeNameAssemblyFormat, clone.TypeNameAssemblyFormat); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.TypeNameAssemblyFormat))); +#pragma warning restore CS0618 // Type or member is obsolete + + Assert.AreEqual(settings.TypeNameAssemblyFormatHandling, clone.TypeNameAssemblyFormatHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.TypeNameAssemblyFormatHandling))); + + Assert.AreEqual(settings.ConstructorHandling, clone.ConstructorHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.ConstructorHandling))); + + Assert.AreEqual(settings.ContractResolver, clone.ContractResolver); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.ContractResolver))); + + Assert.AreEqual(settings.EqualityComparer, clone.EqualityComparer); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.EqualityComparer))); + +#pragma warning disable CS0618 // Type or member is obsolete + Assert.AreEqual(settings.ReferenceResolver, clone.ReferenceResolver); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.ReferenceResolver))); +#pragma warning restore CS0618 // Type or member is obsolete + + Assert.AreEqual(settings.ReferenceResolverProvider, clone.ReferenceResolverProvider); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.ReferenceResolverProvider))); + + Assert.AreEqual(settings.TraceWriter, clone.TraceWriter); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.TraceWriter))); + +#pragma warning disable CS0618 // Type or member is obsolete + Assert.AreEqual(settings.Binder, clone.Binder); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.Binder))); +#pragma warning restore CS0618 // Type or member is obsolete + + Assert.AreEqual(settings.SerializationBinder, clone.SerializationBinder); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.SerializationBinder))); + + Assert.AreEqual(settings.Error, clone.Error); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.Error))); + + Assert.AreEqual(settings.Context, clone.Context); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.Context))); + + Assert.AreEqual(settings.MaxDepth, clone.MaxDepth); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.MaxDepth))); + + Assert.AreEqual(settings.Formatting, clone.Formatting); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.Formatting))); + + Assert.AreEqual(settings.DateTimeZoneHandling, clone.DateTimeZoneHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.DateTimeZoneHandling))); + + Assert.AreEqual(settings.DateParseHandling, clone.DateParseHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.DateParseHandling))); + + Assert.AreEqual(settings.FloatFormatHandling, clone.FloatFormatHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.FloatFormatHandling))); + + Assert.AreEqual(settings.FloatParseHandling, clone.FloatParseHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.FloatParseHandling))); + + Assert.AreEqual(settings.StringEscapeHandling, clone.StringEscapeHandling); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.StringEscapeHandling))); + + Assert.AreEqual(settings.Culture, clone.Culture); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.Culture))); + + Assert.AreEqual(settings.CheckAdditionalContent, clone.CheckAdditionalContent); + Assert.IsTrue(propertyNames.Remove(nameof(JsonSerializerSettings.CheckAdditionalContent))); + + Assert.AreEqual(0, propertyNames.Count); + } + private static int GetDepth(JToken o) { int depth = 1; diff --git a/Src/Newtonsoft.Json/JsonSerializerSettings.cs b/Src/Newtonsoft.Json/JsonSerializerSettings.cs index fc5205dd2..500e1c665 100644 --- a/Src/Newtonsoft.Json/JsonSerializerSettings.cs +++ b/Src/Newtonsoft.Json/JsonSerializerSettings.cs @@ -31,6 +31,12 @@ using Newtonsoft.Json.Serialization; using System.Runtime.Serialization; using System.Diagnostics; +using System.Runtime; +#if !HAVE_LINQ +using Newtonsoft.Json.Utilities.LinqBridge; +#else +using System.Linq; +#endif namespace Newtonsoft.Json { @@ -452,5 +458,44 @@ public JsonSerializerSettings() { Converters = new List(); } + + /// + /// Initializes a new instance of the class + /// using values copied from the passed in . + /// + public JsonSerializerSettings(JsonSerializerSettings original) + { + _floatParseHandling = original._floatParseHandling; + _floatFormatHandling = original._floatFormatHandling; + _dateParseHandling = original._dateParseHandling; + _dateTimeZoneHandling = original._dateTimeZoneHandling; + _dateFormatHandling = original._dateFormatHandling; + _formatting = original._formatting; + _maxDepth = original._maxDepth; + _maxDepthSet = original._maxDepthSet; + _dateFormatString = original._dateFormatString; + _dateFormatStringSet = original._dateFormatStringSet; + _context = original._context; + Error = original.Error; + SerializationBinder = original.SerializationBinder; + TraceWriter = original.TraceWriter; + _culture = original._culture; + ReferenceResolverProvider = original.ReferenceResolverProvider; + EqualityComparer = original.EqualityComparer; + ContractResolver = original.ContractResolver; + _constructorHandling = original._constructorHandling; + _typeNameAssemblyFormatHandling = original._typeNameAssemblyFormatHandling; + _metadataPropertyHandling = original._metadataPropertyHandling; + _typeNameHandling = original._typeNameHandling; + _preserveReferencesHandling = original._preserveReferencesHandling; + Converters = original.Converters.ToList(); + _defaultValueHandling = original._defaultValueHandling; + _nullValueHandling = original._nullValueHandling; + _objectCreationHandling = original._objectCreationHandling; + _missingMemberHandling = original._missingMemberHandling; + _referenceLoopHandling = original._referenceLoopHandling; + _checkAdditionalContent = original._checkAdditionalContent; + _stringEscapeHandling = original._stringEscapeHandling; + } } } \ No newline at end of file From e42c9e4824358b9b38414df0370919c822ed8523 Mon Sep 17 00:00:00 2001 From: AlanLiu90 Date: Mon, 16 May 2022 09:53:06 +0800 Subject: [PATCH 15/30] Fixed rare race condition in name table when deserializing on device with ARM processors (#2602) --- Src/Newtonsoft.Json/DefaultJsonNameTable.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Src/Newtonsoft.Json/DefaultJsonNameTable.cs b/Src/Newtonsoft.Json/DefaultJsonNameTable.cs index 5243160ea..659eefab7 100644 --- a/Src/Newtonsoft.Json/DefaultJsonNameTable.cs +++ b/Src/Newtonsoft.Json/DefaultJsonNameTable.cs @@ -24,6 +24,7 @@ #endregion using System; +using System.Threading; namespace Newtonsoft.Json { @@ -78,7 +79,12 @@ public DefaultJsonNameTable() hashCode -= hashCode >> 5; // make sure index is evaluated before accessing _entries, otherwise potential race condition causing IndexOutOfRangeException - var index = hashCode & _mask; +#if NET20 || NET35 || NET40 + int mask = Thread.VolatileRead(ref _mask); +#else + int mask = Volatile.Read(ref _mask); +#endif + var index = hashCode & mask; var entries = _entries; for (Entry entry = entries[index]; entry != null; entry = entry.Next) @@ -160,7 +166,12 @@ private void Grow() } } _entries = newEntries; - _mask = newMask; + +#if NET20 || NET35 || NET40 + Thread.VolatileWrite(ref _mask, newMask); +#else + Volatile.Write(ref _mask, newMask); +#endif } private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) From bf2e2a78e8febf0006ec647f9bde3aa5bbe0ce72 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Mon, 16 May 2022 16:12:52 +0800 Subject: [PATCH 16/30] Add .NET 6 target (#2677) --- Build/build.ps1 | 3 +- .../Linq/JObjectTests.cs | 2 +- .../Newtonsoft.Json.Tests.csproj | 29 +++- .../Converters/BinaryConverter.cs | 4 +- .../Converters/DataSetConverter.cs | 4 +- .../Converters/DataTableConverter.cs | 6 +- .../Converters/DiscriminatedUnionConverter.cs | 2 +- .../Converters/EntityKeyMemberConverter.cs | 2 +- .../Converters/ExpandoObjectConverter.cs | 2 +- .../Converters/IsoDateTimeConverter.cs | 4 +- .../Converters/JavaScriptDateTimeConverter.cs | 2 +- .../Converters/KeyValuePairConverter.cs | 6 +- .../Converters/RegexConverter.cs | 2 +- .../Converters/StringEnumConverter.cs | 4 +- .../Converters/UnixDateTimeConverter.cs | 2 +- .../Converters/XmlNodeConverter.cs | 140 ++++++++++-------- Src/Newtonsoft.Json/JsonConvert.cs | 4 +- Src/Newtonsoft.Json/JsonReader.cs | 4 +- Src/Newtonsoft.Json/JsonTextReader.Async.cs | 6 +- Src/Newtonsoft.Json/JsonTextReader.cs | 1 + Src/Newtonsoft.Json/JsonTextWriter.Async.cs | 20 +-- Src/Newtonsoft.Json/JsonTextWriter.cs | 7 + Src/Newtonsoft.Json/JsonWriter.Async.cs | 10 +- Src/Newtonsoft.Json/JsonWriter.cs | 4 +- Src/Newtonsoft.Json/Linq/Extensions.cs | 4 +- Src/Newtonsoft.Json/Linq/JConstructor.cs | 8 +- Src/Newtonsoft.Json/Linq/JContainer.Async.cs | 2 +- Src/Newtonsoft.Json/Linq/JContainer.cs | 25 ++-- Src/Newtonsoft.Json/Linq/JEnumerable.cs | 2 +- Src/Newtonsoft.Json/Linq/JObject.Async.cs | 4 +- Src/Newtonsoft.Json/Linq/JObject.cs | 6 +- Src/Newtonsoft.Json/Linq/JProperty.Async.cs | 2 +- Src/Newtonsoft.Json/Linq/JProperty.cs | 8 +- .../Linq/JPropertyDescriptor.cs | 4 +- .../Linq/JPropertyKeyedCollection.cs | 4 +- Src/Newtonsoft.Json/Linq/JToken.cs | 18 +-- .../Linq/JTokenEqualityComparer.cs | 2 +- Src/Newtonsoft.Json/Linq/JValue.cs | 50 +++---- .../Linq/JsonPath/QueryExpression.cs | 2 +- Src/Newtonsoft.Json/Newtonsoft.Json.csproj | 8 +- .../Schema/JsonSchemaBuilder.cs | 11 +- .../CamelCasePropertyNamesContractResolver.cs | 2 +- .../Serialization/DefaultContractResolver.cs | 40 ++--- .../Serialization/DefaultReferenceResolver.cs | 6 +- .../DefaultSerializationBinder.cs | 10 +- .../Serialization/JsonArrayContract.cs | 5 +- .../Serialization/JsonContract.cs | 2 +- .../Serialization/JsonDictionaryContract.cs | 4 +- .../Serialization/JsonFormatterConverter.cs | 8 +- .../Serialization/JsonPropertyCollection.cs | 4 +- .../JsonSerializerInternalBase.cs | 2 +- .../JsonSerializerInternalReader.cs | 28 ++-- .../JsonSerializerInternalWriter.cs | 12 +- .../Serialization/JsonTypeReflector.cs | 19 ++- .../Serialization/NamingStrategy.cs | 2 +- .../SerializationBinderAdapter.cs | 2 +- Src/Newtonsoft.Json/Utilities/AsyncUtils.cs | 6 +- .../Utilities/Base64Encoder.cs | 10 +- .../Utilities/BidirectionalDictionary.cs | 11 +- .../Utilities/CollectionUtils.cs | 12 +- .../Utilities/CollectionWrapper.cs | 30 ++-- Src/Newtonsoft.Json/Utilities/ConvertUtils.cs | 8 +- .../Utilities/DictionaryWrapper.cs | 34 ++--- .../Utilities/DynamicProxyMetaObject.cs | 16 +- .../DynamicReflectionDelegateFactory.cs | 38 ++--- Src/Newtonsoft.Json/Utilities/DynamicUtils.cs | 24 +-- Src/Newtonsoft.Json/Utilities/EnumUtils.cs | 4 +- .../ExpressionReflectionDelegateFactory.cs | 22 +-- Src/Newtonsoft.Json/Utilities/FSharpUtils.cs | 26 ++-- .../Utilities/ImmutableCollectionsUtils.cs | 20 +-- .../Utilities/JavaScriptUtils.cs | 5 +- .../LateBoundReflectionDelegateFactory.cs | 10 +- .../Utilities/MiscellaneousUtils.cs | 4 +- .../Utilities/NullableAttributes.cs | 6 +- .../Utilities/ReflectionUtils.cs | 34 +++-- Src/Newtonsoft.Json/Utilities/StringBuffer.cs | 2 +- Src/Newtonsoft.Json/Utilities/StringUtils.cs | 20 ++- .../Utilities/StructMultiKey.cs | 2 +- .../Utilities/ThreadSafeStore.cs | 2 +- .../Utilities/TypeExtensions.cs | 6 +- 80 files changed, 520 insertions(+), 408 deletions(-) diff --git a/Build/build.ps1 b/Build/build.ps1 index 7491dc6ff..d5927e260 100644 --- a/Build/build.ps1 +++ b/Build/build.ps1 @@ -32,7 +32,8 @@ $nunitConsolePath = "$buildDir\Temp\NUnit.ConsoleRunner.$nunitConsoleVersion" $builds = @( - @{Framework = "netstandard2.0"; TestsFunction = "NetCliTests"; TestFramework = "net6.0"; Enabled=$true}, + @{Framework = "net6.0"; TestsFunction = "NetCliTests"; TestFramework = "net6.0"; Enabled=$true}, + @{Framework = "netstandard2.0"; TestsFunction = "NetCliTests"; TestFramework = "net5.0"; Enabled=$true}, @{Framework = "netstandard1.3"; TestsFunction = "NetCliTests"; TestFramework = "netcoreapp3.1"; Enabled=$true}, @{Framework = "netstandard1.0"; TestsFunction = "NetCliTests"; TestFramework = "netcoreapp2.1"; Enabled=$true}, @{Framework = "net45"; TestsFunction = "NUnitTests"; TestFramework = "net46"; NUnitFramework="net-4.0"; Enabled=$true}, diff --git a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs index 03f69e082..47d7a078f 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs @@ -1439,7 +1439,7 @@ public void ITypedListGetItemProperties() ITypedList l = new JObject(p1, p2); PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null); - Assert.IsNull(propertyDescriptors); + Assert.AreEqual(0, propertyDescriptors.Count); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj index f1166b1a2..d716b0a87 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -1,6 +1,6 @@  - net46;net40;net35;net20;net6.0;netcoreapp3.1;netcoreapp2.1 + net46;net40;net35;net20;net5.0;net6.0;netcoreapp3.1;netcoreapp2.1 $(TestFrameworks) 9.0 1.0 @@ -13,7 +13,7 @@ Newtonsoft.Json.Tests false - Full + Full false @@ -109,7 +109,7 @@ NET20;$(AdditionalConstants) - + @@ -124,12 +124,33 @@ - + Json.NET Tests .NET Standard 2.0 .NETStandard,Version=v2.0 NETSTANDARD2_0;DNXCORE50;PORTABLE;HAVE_BENCHMARKS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) + + + + + + + + + + + + + + + + + Json.NET Tests .NET 6.0 + net6.0 + NETSTANDARD2_0;DNXCORE50;PORTABLE;HAVE_BENCHMARKS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) + + diff --git a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs index 7390503a2..47833a2ac 100644 --- a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs +++ b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs @@ -126,7 +126,7 @@ private static void EnsureReflectionObject(Type t) { // current token is already at base64 string // unable to call ReadAsBytes so do it the old fashion way - string encodedData = reader.Value!.ToString(); + string encodedData = reader.Value!.ToString()!; data = Convert.FromBase64String(encodedData); } else @@ -135,7 +135,7 @@ private static void EnsureReflectionObject(Type t) } Type t = (ReflectionUtils.IsNullableType(objectType)) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; #if HAVE_LINQ diff --git a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs index 61bb62536..214728e67 100644 --- a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs @@ -84,7 +84,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer // handle typed datasets DataSet ds = (objectType == typeof(DataSet)) ? new DataSet() - : (DataSet)Activator.CreateInstance(objectType); + : (DataSet)Activator.CreateInstance(objectType)!; DataTableConverter converter = new DataTableConverter(); @@ -92,7 +92,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer while (reader.TokenType == JsonToken.PropertyName) { - DataTable dt = ds.Tables[(string)reader.Value!]; + DataTable? dt = ds.Tables[(string)reader.Value!]; bool exists = (dt != null); dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer)!; diff --git a/Src/Newtonsoft.Json/Converters/DataTableConverter.cs b/Src/Newtonsoft.Json/Converters/DataTableConverter.cs index 7f8c529e4..1a32e5121 100644 --- a/Src/Newtonsoft.Json/Converters/DataTableConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DataTableConverter.cs @@ -99,7 +99,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer // handle typed datasets dt = (objectType == typeof(DataTable)) ? new DataTable() - : (DataTable)Activator.CreateInstance(objectType); + : (DataTable)Activator.CreateInstance(objectType)!; } // DataTable is inside a DataSet @@ -144,7 +144,7 @@ private static void CreateRow(JsonReader reader, DataTable dt, JsonSerializer se reader.ReadAndAssert(); - DataColumn column = dt.Columns[columnName]; + DataColumn? column = dt.Columns[columnName]; if (column == null) { Type columnType = GetColumnDataType(reader); @@ -185,7 +185,7 @@ private static void CreateRow(JsonReader reader, DataTable dt, JsonSerializer se reader.ReadAndAssert(); } - Array destinationArray = Array.CreateInstance(column.DataType.GetElementType(), o.Count); + Array destinationArray = Array.CreateInstance(column.DataType.GetElementType()!, o.Count); ((IList)o).CopyTo(destinationArray, 0); dr[columnName] = destinationArray; diff --git a/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs b/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs index 5adb40b27..c4c5d08a0 100644 --- a/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs @@ -182,7 +182,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer while (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (string.Equals(propertyName, CasePropertyName, StringComparison.OrdinalIgnoreCase)) { reader.ReadAndAssert(); diff --git a/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs b/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs index 4670dba40..757c8fac6 100644 --- a/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs +++ b/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs @@ -129,7 +129,7 @@ private static void ReadAndAssertProperty(JsonReader reader, string propertyName reader.ReadAndAssert(); string? type = reader.Value?.ToString(); - Type t = Type.GetType(type); + Type t = Type.GetType(type!)!; ReadAndAssertProperty(reader, ValuePropertyName); reader.ReadAndAssert(); diff --git a/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs b/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs index 0b5153fd4..5a674b8c1 100644 --- a/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs +++ b/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs @@ -119,7 +119,7 @@ private object ReadObject(JsonReader reader) switch (reader.TokenType) { case JsonToken.PropertyName: - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (!reader.Read()) { diff --git a/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs index d9c8ee235..de9b1bb59 100644 --- a/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs @@ -133,7 +133,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer #if HAVE_DATE_TIME_OFFSET Type t = (nullable) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; #endif @@ -167,6 +167,8 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer return null; } + MiscellaneousUtils.Assert(dateText != null); + #if HAVE_DATE_TIME_OFFSET if (t == typeof(DateTimeOffset)) { diff --git a/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs index 34082451f..ff1231f25 100644 --- a/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs @@ -98,7 +98,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer #if HAVE_DATE_TIME_OFFSET Type t = (ReflectionUtils.IsNullableType(objectType)) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; if (t == typeof(DateTimeOffset)) { diff --git a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs index 0f12f1fab..0221e9337 100644 --- a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs +++ b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs @@ -102,7 +102,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer reader.ReadAndAssert(); Type t = ReflectionUtils.IsNullableType(objectType) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; ReflectionObject reflectionObject = ReflectionObjectPerType.Get(t); @@ -111,7 +111,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer while (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase)) { reader.ReadForTypeAndAssert(keyContract, false); @@ -145,7 +145,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer public override bool CanConvert(Type objectType) { Type t = (ReflectionUtils.IsNullableType(objectType)) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; if (t.IsValueType() && t.IsGenericType()) diff --git a/Src/Newtonsoft.Json/Converters/RegexConverter.cs b/Src/Newtonsoft.Json/Converters/RegexConverter.cs index 8bf6e9f9d..13db1bb57 100644 --- a/Src/Newtonsoft.Json/Converters/RegexConverter.cs +++ b/Src/Newtonsoft.Json/Converters/RegexConverter.cs @@ -179,7 +179,7 @@ private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer) switch (reader.TokenType) { case JsonToken.PropertyName: - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (!reader.Read()) { diff --git a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs index 9ba6b6324..a98400808 100644 --- a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs +++ b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs @@ -222,7 +222,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer } bool isNullable = ReflectionUtils.IsNullableType(objectType); - Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType; + Type t = isNullable ? Nullable.GetUnderlyingType(objectType)! : objectType; try { @@ -267,7 +267,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer public override bool CanConvert(Type objectType) { Type t = (ReflectionUtils.IsNullableType(objectType)) - ? Nullable.GetUnderlyingType(objectType) + ? Nullable.GetUnderlyingType(objectType)! : objectType; return t.IsEnum(); diff --git a/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs index a211813dc..7d0700e0c 100644 --- a/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs @@ -144,7 +144,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer DateTime d = UnixEpoch.AddSeconds(seconds); #if HAVE_DATE_TIME_OFFSET - Type t = (nullable) + Type? t = (nullable) ? Nullable.GetUnderlyingType(objectType) : objectType; if (t == typeof(DateTimeOffset)) diff --git a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs index 2abb677a4..12bde5157 100644 --- a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs @@ -79,19 +79,19 @@ 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)); } @@ -114,7 +114,7 @@ public IXmlNode CreateAttribute(string name, string? value) return attribute; } - public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value) + public IXmlNode CreateAttribute(string qualifiedName, string? namespaceUri, string? value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceUri)); attribute.Value = value; @@ -153,7 +153,7 @@ public void SetAttributeNode(IXmlNode attribute) _element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode!); } - public string GetPrefixOfNamespace(string namespaceUri) + public string? GetPrefixOfNamespace(string namespaceUri) { return _element.GetPrefixOfNamespace(namespaceUri); } @@ -171,15 +171,15 @@ public XmlDeclarationWrapper(XmlDeclaration declaration) _declaration = declaration; } - public string Version => _declaration.Version; + public string? Version => _declaration.Version; - public string Encoding + public string? Encoding { get => _declaration.Encoding; set => _declaration.Encoding = value; } - public string Standalone + public string? Standalone { get => _declaration.Standalone; set => _declaration.Standalone = value; @@ -199,11 +199,11 @@ public XmlDocumentTypeWrapper(XmlDocumentType documentType) public string Name => _documentType.Name; - public string System => _documentType.SystemId; + public string? System => _documentType.SystemId; - public string Public => _documentType.PublicId; + public string? Public => _documentType.PublicId; - public string InternalSubset => _documentType.InternalSubset; + public string? InternalSubset => _documentType.InternalSubset; public override string? LocalName => "DOCTYPE"; } @@ -285,7 +285,7 @@ public List Attributes } else { - _attributes = new List(_node.Attributes.Count); + _attributes = new List(_node.Attributes!.Count); foreach (XmlAttribute attribute in _node.Attributes) { _attributes.Add(WrapNode(attribute)); @@ -314,7 +314,7 @@ public IXmlNode? ParentNode { get { - XmlNode node = _node is XmlAttribute attribute ? attribute.OwnerElement : _node.ParentNode; + XmlNode? node = _node is XmlAttribute attribute ? attribute.OwnerElement : _node.ParentNode; if (node == null) { @@ -354,38 +354,38 @@ internal interface IXmlDocument : IXmlNode IXmlNode CreateCDataSection(string? data); IXmlNode CreateWhitespace(string? text); IXmlNode CreateSignificantWhitespace(string? text); - IXmlNode CreateXmlDeclaration(string? version, string? encoding, string? standalone); + IXmlNode CreateXmlDeclaration(string version, string? encoding, string? standalone); #if HAVE_XML_DOCUMENT_TYPE - IXmlNode CreateXmlDocumentType(string? name, string? publicId, string? systemId, string? internalSubset); + IXmlNode CreateXmlDocumentType(string name, string? publicId, string? systemId, string? internalSubset); #endif - IXmlNode CreateProcessingInstruction(string target, string? data); + IXmlNode CreateProcessingInstruction(string target, string data); IXmlElement CreateElement(string elementName); IXmlElement CreateElement(string qualifiedName, string namespaceUri); - IXmlNode CreateAttribute(string name, string? value); - IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value); + IXmlNode CreateAttribute(string name, string value); + IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value); IXmlElement? DocumentElement { get; } } internal interface IXmlDeclaration : IXmlNode { - string Version { get; } - string Encoding { get; set; } - string Standalone { get; set; } + string? Version { get; } + string? Encoding { get; set; } + string? Standalone { get; set; } } internal interface IXmlDocumentType : IXmlNode { string Name { get; } - string System { get; } - string Public { get; } - string InternalSubset { get; } + string? System { get; } + string? Public { get; } + string? InternalSubset { get; } } internal interface IXmlElement : IXmlNode { void SetAttributeNode(IXmlNode attribute); - string GetPrefixOfNamespace(string namespaceUri); + string? GetPrefixOfNamespace(string namespaceUri); bool IsEmpty { get; } } @@ -417,15 +417,15 @@ public XDeclarationWrapper(XDeclaration declaration) public override XmlNodeType NodeType => XmlNodeType.XmlDeclaration; - public string Version => Declaration.Version; + public string? Version => Declaration.Version; - public string Encoding + public string? Encoding { get => Declaration.Encoding; set => Declaration.Encoding = value; } - public string Standalone + public string? Standalone { get => Declaration.Standalone; set => Declaration.Standalone = value; @@ -444,11 +444,11 @@ public XDocumentTypeWrapper(XDocumentType documentType) public string Name => _documentType.Name; - public string System => _documentType.SystemId; + public string? System => _documentType.SystemId; - public string Public => _documentType.PublicId; + public string? Public => _documentType.PublicId; - public string InternalSubset => _documentType.InternalSubset; + public string? InternalSubset => _documentType.InternalSubset; public override string? LocalName => "DOCTYPE"; } @@ -491,40 +491,40 @@ protected override bool HasChildNodes public IXmlNode CreateComment(string? text) { - return new XObjectWrapper(new XComment(text)); + return new XObjectWrapper(new XComment(text!)); } public IXmlNode CreateTextNode(string? text) { - return new XObjectWrapper(new XText(text)); + return new XObjectWrapper(new XText(text!)); } public IXmlNode CreateCDataSection(string? data) { - return new XObjectWrapper(new XCData(data)); + return new XObjectWrapper(new XCData(data!)); } public IXmlNode CreateWhitespace(string? text) { - return new XObjectWrapper(new XText(text)); + return new XObjectWrapper(new XText(text!)); } public IXmlNode CreateSignificantWhitespace(string? text) { - return new XObjectWrapper(new XText(text)); + return new XObjectWrapper(new XText(text!)); } - public IXmlNode CreateXmlDeclaration(string? version, string? encoding, string? standalone) + public IXmlNode CreateXmlDeclaration(string version, string? encoding, string? standalone) { return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone)); } - public IXmlNode CreateXmlDocumentType(string? name, string? publicId, string? systemId, string? internalSubset) + public IXmlNode CreateXmlDocumentType(string name, string? publicId, string? systemId, string? internalSubset) { return new XDocumentTypeWrapper(new XDocumentType(name, publicId, systemId, internalSubset)); } - public IXmlNode CreateProcessingInstruction(string target, string? data) + public IXmlNode CreateProcessingInstruction(string target, string data) { return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data)); } @@ -540,12 +540,12 @@ public IXmlElement CreateElement(string qualifiedName, string namespaceUri) return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri))); } - public IXmlNode CreateAttribute(string name, string? value) + public IXmlNode CreateAttribute(string name, string value) { return new XAttributeWrapper(new XAttribute(name, value)); } - public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value) + public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value)); @@ -590,7 +590,7 @@ public XTextWrapper(XText text) public override string? Value { get => Text.Value; - set => Text.Value = value; + set => Text.Value = value ?? string.Empty; } public override IXmlNode? ParentNode @@ -619,7 +619,7 @@ public XCommentWrapper(XComment text) public override string? Value { get => Text.Value; - set => Text.Value = value; + set => Text.Value = value ?? string.Empty; } public override IXmlNode? ParentNode @@ -650,7 +650,7 @@ public XProcessingInstructionWrapper(XProcessingInstruction processingInstructio public override string? Value { get => ProcessingInstruction.Data; - set => ProcessingInstruction.Data = value; + set => ProcessingInstruction.Data = value ?? string.Empty; } } @@ -807,7 +807,7 @@ public XAttributeWrapper(XAttribute attribute) public override string? Value { get => Attribute.Value; - set => Attribute.Value = value; + set => Attribute.Value = value ?? string.Empty; } public override string? LocalName => Attribute.Name.LocalName; @@ -919,14 +919,14 @@ public override IXmlNode AppendChild(IXmlNode newChild) public override string? Value { get => Element.Value; - set => Element.Value = value; + set => Element.Value = value ?? string.Empty; } public override string? LocalName => Element.Name.LocalName; public override string? NamespaceUri => Element.Name.NamespaceName; - public string GetPrefixOfNamespace(string namespaceUri) + public string? GetPrefixOfNamespace(string namespaceUri) { return Element.GetPrefixOfNamespace(namespaceUri); } @@ -1059,7 +1059,7 @@ private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) { if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns") { - manager.AddNamespace(attribute.LocalName, attribute.Value); + manager.AddNamespace(attribute.LocalName!, attribute.Value!); } } } @@ -1078,7 +1078,7 @@ private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager) } else { - return XmlConvert.DecodeName(node.LocalName); + return XmlConvert.DecodeName(node.LocalName)!; } } @@ -1131,7 +1131,7 @@ private bool IsArray(IXmlNode node) { if (attribute.LocalName == "Array" && attribute.NamespaceUri == JsonNamespaceUri) { - return XmlConvert.ToBoolean(attribute.Value); + return XmlConvert.ToBoolean(attribute.Value!); } } @@ -1201,7 +1201,7 @@ private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespac } else { - if (!nodesGroupedByName.TryGetValue(currentNodeName, out object value)) + if (!nodesGroupedByName.TryGetValue(currentNodeName, out object? value)) { nodesGroupedByName.Add(currentNodeName, childNode); } @@ -1314,7 +1314,7 @@ private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/") { string namespacePrefix = (attribute.LocalName != "xmlns") - ? XmlConvert.DecodeName(attribute.LocalName) + ? XmlConvert.DecodeName(attribute.LocalName)! : string.Empty; string? namespaceUri = attribute.Value; if (namespaceUri == null) @@ -1654,7 +1654,7 @@ private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode curr case JsonTypeReflector.TypePropertyName: case JsonTypeReflector.ValuePropertyName: string attributeName = propertyName.Substring(1); - string attributePrefix = manager.LookupPrefix(JsonNamespaceUri); + string? attributePrefix = manager.LookupPrefix(JsonNamespaceUri); AddAttribute(reader, document, currentNode, propertyName, attributeName, manager, attributePrefix); return; } @@ -1685,7 +1685,9 @@ private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode cu string encodedName = XmlConvert.EncodeName(nameValue.Key); string? attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); - IXmlNode attribute = (!StringUtils.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value) : document.CreateAttribute(encodedName, nameValue.Value); + IXmlNode attribute = (!StringUtils.IsNullOrEmpty(attributePrefix)) + ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value!) + : document.CreateAttribute(encodedName, nameValue.Value!); element.SetAttributeNode(attribute); } @@ -1731,10 +1733,10 @@ private static void AddAttribute(JsonReader reader, IXmlDocument document, IXmlN } string encodedName = XmlConvert.EncodeName(attributeName); - string? attributeValue = ConvertTokenToXmlValue(reader); + string attributeValue = ConvertTokenToXmlValue(reader)!; IXmlNode attribute = (!StringUtils.IsNullOrEmpty(attributePrefix)) - ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix), attributeValue) + ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix)!, attributeValue) : document.CreateAttribute(encodedName, attributeValue); ((IXmlElement)currentNode).SetAttributeNode(attribute); @@ -1874,7 +1876,7 @@ private bool ShouldReadInto(JsonReader reader) switch (reader.TokenType) { case JsonToken.PropertyName: - string attributeName = reader.Value!.ToString(); + string attributeName = reader.Value!.ToString()!; if (!StringUtils.IsNullOrEmpty(attributeName)) { @@ -1896,7 +1898,7 @@ private bool ShouldReadInto(JsonReader reader) if (IsNamespaceAttribute(attributeName, out string? namespacePrefix)) { - manager.AddNamespace(namespacePrefix, attributeValue); + manager.AddNamespace(namespacePrefix, attributeValue!); } break; case '$': @@ -1909,7 +1911,7 @@ private bool ShouldReadInto(JsonReader reader) case JsonTypeReflector.ValuePropertyName: // check that JsonNamespaceUri is in scope // if it isn't then add it to document and namespace manager - string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri); + string? jsonPrefix = manager.LookupPrefix(JsonNamespaceUri); if (jsonPrefix == null) { if (attributeNameValues == null) @@ -2008,12 +2010,17 @@ private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNod } } + if (version == null) + { + throw JsonSerializationException.Create(reader, "Version not specified for XML declaration."); + } + IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone); currentNode.AppendChild(declaration); } else { - IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), ConvertTokenToXmlValue(reader)); + IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), ConvertTokenToXmlValue(reader)!); currentNode.AppendChild(instruction); } } @@ -2050,6 +2057,11 @@ private void CreateDocumentType(JsonReader reader, IXmlDocument document, IXmlNo } } + if (name == null) + { + throw JsonSerializationException.Create(reader, "Name not specified for XML document type."); + } + IXmlNode documentType = document.CreateXmlDocumentType(name, publicId, systemId, internalSubset); currentNode.AppendChild(documentType); } @@ -2058,7 +2070,7 @@ private void CreateDocumentType(JsonReader reader, IXmlDocument document, IXmlNo private IXmlElement CreateElement(string elementName, IXmlDocument document, string? elementPrefix, XmlNamespaceManager manager) { string encodeName = EncodeSpecialCharacters ? XmlConvert.EncodeLocalName(elementName) : XmlConvert.EncodeName(elementName); - string ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); + string? ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); IXmlElement element = (!StringUtils.IsNullOrEmpty(ns)) ? document.CreateElement(encodeName, ns) : document.CreateElement(encodeName); @@ -2077,7 +2089,7 @@ private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamesp throw JsonSerializationException.Create(reader, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifying a DeserializeRootElementName."); } - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; reader.ReadAndAssert(); if (reader.TokenType == JsonToken.StartArray) @@ -2092,7 +2104,7 @@ private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamesp if (count == 1 && WriteArrayAttribute) { MiscellaneousUtils.GetQualifiedNameParts(propertyName, out string? elementPrefix, out string localName); - string ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); + string? ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); foreach (IXmlNode childNode in currentNode.ChildNodes) { @@ -2110,7 +2122,7 @@ private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamesp } continue; case JsonToken.StartConstructor: - string constructorName = reader.Value!.ToString(); + string constructorName = reader.Value!.ToString()!; while (reader.Read() && reader.TokenType != JsonToken.EndConstructor) { diff --git a/Src/Newtonsoft.Json/JsonConvert.cs b/Src/Newtonsoft.Json/JsonConvert.cs index 5bf7e2a62..95019e2b7 100644 --- a/Src/Newtonsoft.Json/JsonConvert.cs +++ b/Src/Newtonsoft.Json/JsonConvert.cs @@ -302,7 +302,7 @@ internal static string ToString(double value, FloatFormatHandling floatFormatHan private static string EnsureDecimalPlace(double value, string text) { - if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1) + if (double.IsNaN(value) || double.IsInfinity(value) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1) { return text; } @@ -312,7 +312,7 @@ private static string EnsureDecimalPlace(double value, string text) private static string EnsureDecimalPlace(string text) { - if (text.IndexOf('.') != -1) + if (StringUtils.IndexOf(text, '.') != -1) { return text; } diff --git a/Src/Newtonsoft.Json/JsonReader.cs b/Src/Newtonsoft.Json/JsonReader.cs index 2351b1879..e368afc15 100644 --- a/Src/Newtonsoft.Json/JsonReader.cs +++ b/Src/Newtonsoft.Json/JsonReader.cs @@ -496,7 +496,7 @@ private JsonContainerType Peek() } else { - s = v is Uri uri ? uri.OriginalString : v.ToString(); + s = v is Uri uri ? uri.OriginalString : v.ToString()!; } SetToken(JsonToken.String, s, false); @@ -940,7 +940,7 @@ internal void ReadIntoWrappedTypeObject() if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName) { ReaderReadAndAssert(); - if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) + if (Value != null && Value.ToString()!.StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) diff --git a/Src/Newtonsoft.Json/JsonTextReader.Async.cs b/Src/Newtonsoft.Json/JsonTextReader.Async.cs index 7963f5b90..8974e700a 100644 --- a/Src/Newtonsoft.Json/JsonTextReader.Async.cs +++ b/Src/Newtonsoft.Json/JsonTextReader.Async.cs @@ -79,7 +79,7 @@ internal Task DoReadAsync(CancellationToken cancellationToken) return ParseObjectAsync(cancellationToken); case State.PostValue: Task task = ParsePostValueAsync(false, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { if (task.Result) { @@ -542,7 +542,7 @@ private Task ProcessCarriageReturnAsync(bool append, CancellationToken cancellat _charPos++; Task task = EnsureCharsAsync(1, append, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { SetNewLine(task.Result); return AsyncUtils.CompletedTask; @@ -1680,7 +1680,7 @@ private async Task ReadIntoWrappedTypeObjectAsync(CancellationToken cancellation if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName) { await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false); - if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) + if (Value != null && Value.ToString()!.StartsWith("System.Byte[]", StringComparison.Ordinal)) { await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) diff --git a/Src/Newtonsoft.Json/JsonTextReader.cs b/Src/Newtonsoft.Json/JsonTextReader.cs index 6b107b0e0..925f4b6b2 100644 --- a/Src/Newtonsoft.Json/JsonTextReader.cs +++ b/Src/Newtonsoft.Json/JsonTextReader.cs @@ -2353,6 +2353,7 @@ private void EndComment(bool setToken, int initialPosition, int endPosition) { if (setToken) { + MiscellaneousUtils.Assert(_chars != null); SetToken(JsonToken.Comment, new string(_chars, initialPosition, endPosition - initialPosition)); } } diff --git a/Src/Newtonsoft.Json/JsonTextWriter.Async.cs b/Src/Newtonsoft.Json/JsonTextWriter.Async.cs index c1c763e9e..f3ac2398d 100644 --- a/Src/Newtonsoft.Json/JsonTextWriter.Async.cs +++ b/Src/Newtonsoft.Json/JsonTextWriter.Async.cs @@ -190,7 +190,7 @@ private async Task WriteIndentAsync(int currentIndentCount, int newLineLen, Canc private Task WriteValueInternalAsync(JsonToken token, string value, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(token, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return _writer.WriteAsync(value, cancellationToken); } @@ -270,7 +270,7 @@ private Task WriteDigitsAsync(ulong uvalue, bool negative, CancellationToken can private Task WriteIntegerValueAsync(ulong uvalue, bool negative, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.Integer, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return WriteDigitsAsync(uvalue, negative, cancellationToken); } @@ -321,13 +321,13 @@ public override Task WritePropertyNameAsync(string name, CancellationToken cance internal Task DoWritePropertyNameAsync(string name, CancellationToken cancellationToken) { Task task = InternalWritePropertyNameAsync(name, cancellationToken); - if (!task.IsCompletedSucessfully()) + if (!task.IsCompletedSuccessfully()) { return DoWritePropertyNameAsync(task, name, cancellationToken); } task = WriteEscapedStringAsync(name, _quoteName, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return _writer.WriteAsync(':', cancellationToken); } @@ -399,7 +399,7 @@ public override Task WriteStartArrayAsync(CancellationToken cancellationToken = internal Task DoWriteStartArrayAsync(CancellationToken cancellationToken) { Task task = InternalWriteStartAsync(JsonToken.StartArray, JsonContainerType.Array, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return _writer.WriteAsync('[', cancellationToken); } @@ -429,7 +429,7 @@ public override Task WriteStartObjectAsync(CancellationToken cancellationToken = internal Task DoWriteStartObjectAsync(CancellationToken cancellationToken) { Task task = InternalWriteStartAsync(JsonToken.StartObject, JsonContainerType.Object, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return _writer.WriteAsync('{', cancellationToken); } @@ -481,7 +481,7 @@ public override Task WriteUndefinedAsync(CancellationToken cancellationToken = d internal Task DoWriteUndefinedAsync(CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.Undefined, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return _writer.WriteAsync(JsonConvert.Undefined, cancellationToken); } @@ -1058,7 +1058,7 @@ public override Task WriteValueAsync(string? value, CancellationToken cancellati internal Task DoWriteValueAsync(string? value, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.String, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return value == null ? _writer.WriteAsync(JsonConvert.Null, cancellationToken) : WriteEscapedStringAsync(value, true, cancellationToken); } @@ -1193,7 +1193,7 @@ public override Task WriteValueAsync(Uri? value, CancellationToken cancellationT internal Task WriteValueNotNullAsync(Uri value, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.String, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return WriteEscapedStringAsync(value.OriginalString, true, cancellationToken); } @@ -1314,7 +1314,7 @@ internal Task DoWriteRawValueAsync(string? json, CancellationToken cancellationT { UpdateScopeWithFinishedValue(); Task task = AutoCompleteAsync(JsonToken.Undefined, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return WriteRawAsync(json, cancellationToken); } diff --git a/Src/Newtonsoft.Json/JsonTextWriter.cs b/Src/Newtonsoft.Json/JsonTextWriter.cs index b08dfb48d..888bb04d1 100644 --- a/Src/Newtonsoft.Json/JsonTextWriter.cs +++ b/Src/Newtonsoft.Json/JsonTextWriter.cs @@ -325,6 +325,7 @@ protected override void WriteIndent() int newLineLen = SetIndentChars(); + MiscellaneousUtils.Assert(_indentChars != null); _writer.Write(_indentChars, 0, newLineLen + Math.Min(currentIndentCount, IndentCharBufferSize)); while ((currentIndentCount -= IndentCharBufferSize) > 0) @@ -637,6 +638,7 @@ public override void WriteValue(DateTime value) { int length = WriteValueToBuffer(value); + MiscellaneousUtils.Assert(_writeBuffer != null); _writer.Write(_writeBuffer, 0, length); } else @@ -692,6 +694,7 @@ public override void WriteValue(DateTimeOffset value) { int length = WriteValueToBuffer(value); + MiscellaneousUtils.Assert(_writeBuffer != null); _writer.Write(_writeBuffer, 0, length); } else @@ -829,6 +832,8 @@ private void WriteIntegerValue(ulong value, bool negative) else { int length = WriteNumberToBuffer(value, negative); + + MiscellaneousUtils.Assert(_writeBuffer != null); _writer.Write(_writeBuffer, 0, length); } } @@ -887,6 +892,8 @@ private void WriteIntegerValue(uint value, bool negative) else { int length = WriteNumberToBuffer(value, negative); + + MiscellaneousUtils.Assert(_writeBuffer != null); _writer.Write(_writeBuffer, 0, length); } } diff --git a/Src/Newtonsoft.Json/JsonWriter.Async.cs b/Src/Newtonsoft.Json/JsonWriter.Async.cs index 750d29271..4610594c3 100644 --- a/Src/Newtonsoft.Json/JsonWriter.Async.cs +++ b/Src/Newtonsoft.Json/JsonWriter.Async.cs @@ -291,7 +291,7 @@ internal Task InternalWriteEndAsync(JsonContainerType type, CancellationToken ca if (_currentState == State.Property) { t = WriteNullAsync(cancellationToken); - if (!t.IsCompletedSucessfully()) + if (!t.IsCompletedSuccessfully()) { return AwaitProperty(t, levelsToComplete, token, cancellationToken); } @@ -302,7 +302,7 @@ internal Task InternalWriteEndAsync(JsonContainerType type, CancellationToken ca if (_currentState != State.ObjectStart && _currentState != State.ArrayStart) { t = WriteIndentAsync(cancellationToken); - if (!t.IsCompletedSucessfully()) + if (!t.IsCompletedSuccessfully()) { return AwaitIndent(t, levelsToComplete, token, cancellationToken); } @@ -310,7 +310,7 @@ internal Task InternalWriteEndAsync(JsonContainerType type, CancellationToken ca } t = WriteEndAsync(token, cancellationToken); - if (!t.IsCompletedSucessfully()) + if (!t.IsCompletedSuccessfully()) { return AwaitEnd(t, levelsToComplete, cancellationToken); } @@ -691,10 +691,10 @@ public Task WriteTokenAsync(JsonToken token, object? value, CancellationToken ca return WriteStartArrayAsync(cancellationToken); case JsonToken.StartConstructor: ValidationUtils.ArgumentNotNull(value, nameof(value)); - return WriteStartConstructorAsync(value.ToString(), cancellationToken); + return WriteStartConstructorAsync(value.ToString()!, cancellationToken); case JsonToken.PropertyName: ValidationUtils.ArgumentNotNull(value, nameof(value)); - return WritePropertyNameAsync(value.ToString(), cancellationToken); + return WritePropertyNameAsync(value.ToString()!, cancellationToken); case JsonToken.Comment: return WriteCommentAsync(value?.ToString(), cancellationToken); case JsonToken.Integer: diff --git a/Src/Newtonsoft.Json/JsonWriter.cs b/Src/Newtonsoft.Json/JsonWriter.cs index a68fc8c43..5fd5efe40 100644 --- a/Src/Newtonsoft.Json/JsonWriter.cs +++ b/Src/Newtonsoft.Json/JsonWriter.cs @@ -537,11 +537,11 @@ public void WriteToken(JsonToken token, object? value) break; case JsonToken.StartConstructor: ValidationUtils.ArgumentNotNull(value, nameof(value)); - WriteStartConstructor(value.ToString()); + WriteStartConstructor(value.ToString()!); break; case JsonToken.PropertyName: ValidationUtils.ArgumentNotNull(value, nameof(value)); - WritePropertyName(value.ToString()); + WritePropertyName(value.ToString()!); break; case JsonToken.Comment: WriteComment(value?.ToString()); diff --git a/Src/Newtonsoft.Json/Linq/Extensions.cs b/Src/Newtonsoft.Json/Linq/Extensions.cs index e05fd2621..cd333a2f7 100644 --- a/Src/Newtonsoft.Json/Linq/Extensions.cs +++ b/Src/Newtonsoft.Json/Linq/Extensions.cs @@ -291,10 +291,10 @@ public static IJEnumerable Children(this IEnumerable source) where #pragma warning restore CS8653 // A default expression introduces a null value for a type parameter. } - targetType = Nullable.GetUnderlyingType(targetType); + targetType = Nullable.GetUnderlyingType(targetType)!; } - return (U)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture); + return (U?)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture); } } diff --git a/Src/Newtonsoft.Json/Linq/JConstructor.cs b/Src/Newtonsoft.Json/Linq/JConstructor.cs index 4903c0a24..f2aa86182 100644 --- a/Src/Newtonsoft.Json/Linq/JConstructor.cs +++ b/Src/Newtonsoft.Json/Linq/JConstructor.cs @@ -202,7 +202,13 @@ public override JToken? this[object key] internal override int GetDeepHashCode() { - return (_name?.GetHashCode() ?? 0) ^ ContentsHashCode(); + int hash; +#if HAVE_GETHASHCODE_STRING_COMPARISON + hash = _name?.GetHashCode(StringComparison.Ordinal) ?? 0; +#else + hash = _name?.GetHashCode() ?? 0; +#endif + return hash ^ ContentsHashCode(); } /// diff --git a/Src/Newtonsoft.Json/Linq/JContainer.Async.cs b/Src/Newtonsoft.Json/Linq/JContainer.Async.cs index beb67afd3..8c02b2953 100644 --- a/Src/Newtonsoft.Json/Linq/JContainer.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JContainer.Async.cs @@ -109,7 +109,7 @@ private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings? set parent = parent.Parent; break; case JsonToken.StartConstructor: - JConstructor constructor = new JConstructor(reader.Value!.ToString()); + JConstructor constructor = new JConstructor(reader.Value!.ToString()!); constructor.SetLineInfo(lineInfo, settings); parent.Add(constructor); parent = constructor; diff --git a/Src/Newtonsoft.Json/Linq/JContainer.cs b/Src/Newtonsoft.Json/Linq/JContainer.cs index 07f833bd3..f9447cd5d 100644 --- a/Src/Newtonsoft.Json/Linq/JContainer.cs +++ b/Src/Newtonsoft.Json/Linq/JContainer.cs @@ -84,7 +84,7 @@ public event AddingNewEventHandler AddingNew /// /// Occurs when the items list of the collection has changed, or the collection is reset. /// - public event NotifyCollectionChangedEventHandler CollectionChanged + public event NotifyCollectionChangedEventHandler? CollectionChanged { add { _collectionChanged += value; } remove { _collectionChanged -= value; } @@ -839,7 +839,7 @@ internal void ReadContentFrom(JsonReader r, JsonLoadSettings? settings) parent = parent.Parent; break; case JsonToken.StartConstructor: - JConstructor constructor = new JConstructor(r.Value!.ToString()); + JConstructor constructor = new JConstructor(r.Value!.ToString()!); constructor.SetLineInfo(lineInfo, settings); parent.Add(constructor); parent = constructor; @@ -902,7 +902,7 @@ internal void ReadContentFrom(JsonReader r, JsonLoadSettings? settings) DuplicatePropertyNameHandling duplicatePropertyNameHandling = settings?.DuplicatePropertyNameHandling ?? DuplicatePropertyNameHandling.Replace; JObject parentObject = (JObject)parent; - string propertyName = r.Value!.ToString(); + string propertyName = r.Value!.ToString()!; JProperty? existingPropertyWithName = parentObject.Property(propertyName, StringComparison.Ordinal); if (existingPropertyWithName != null) { @@ -947,10 +947,11 @@ string ITypedList.GetListName(PropertyDescriptor[] listAccessors) return string.Empty; } - PropertyDescriptorCollection? ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) + PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { ICustomTypeDescriptor? d = First as ICustomTypeDescriptor; - return d?.GetProperties(); + + return d?.GetProperties() ?? new PropertyDescriptorCollection(CollectionUtils.ArrayEmpty()); } #endif @@ -1006,7 +1007,7 @@ bool ICollection.Remove(JToken item) } #endregion - private JToken? EnsureValue(object value) + private JToken? EnsureValue(object? value) { if (value == null) { @@ -1022,7 +1023,7 @@ bool ICollection.Remove(JToken item) } #region IList Members - int IList.Add(object value) + int IList.Add(object? value) { Add(EnsureValue(value)); return Count - 1; @@ -1033,17 +1034,17 @@ void IList.Clear() ClearItems(); } - bool IList.Contains(object value) + bool IList.Contains(object? value) { return ContainsItem(EnsureValue(value)); } - int IList.IndexOf(object value) + int IList.IndexOf(object? value) { return IndexOfItem(EnsureValue(value)); } - void IList.Insert(int index, object value) + void IList.Insert(int index, object? value) { InsertItem(index, EnsureValue(value), false); } @@ -1052,7 +1053,7 @@ void IList.Insert(int index, object value) bool IList.IsReadOnly => false; - void IList.Remove(object value) + void IList.Remove(object? value) { RemoveItem(EnsureValue(value)); } @@ -1062,7 +1063,7 @@ void IList.RemoveAt(int index) RemoveItemAt(index); } - object IList.this[int index] + object? IList.this[int index] { get => GetItem(index); set => SetItem(index, EnsureValue(value)); diff --git a/Src/Newtonsoft.Json/Linq/JEnumerable.cs b/Src/Newtonsoft.Json/Linq/JEnumerable.cs index 541f1beba..41de4c333 100644 --- a/Src/Newtonsoft.Json/Linq/JEnumerable.cs +++ b/Src/Newtonsoft.Json/Linq/JEnumerable.cs @@ -111,7 +111,7 @@ public bool Equals(JEnumerable other) /// /// true if the specified is equal to this instance; otherwise, false. /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is JEnumerable enumerable) { diff --git a/Src/Newtonsoft.Json/Linq/JObject.Async.cs b/Src/Newtonsoft.Json/Linq/JObject.Async.cs index d973e8bc1..67f01fe5f 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.Async.cs @@ -45,7 +45,7 @@ public partial class JObject public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { Task t = writer.WriteStartObjectAsync(cancellationToken); - if (!t.IsCompletedSucessfully()) + if (!t.IsCompletedSuccessfully()) { return AwaitProperties(t, 0, writer, cancellationToken, converters); } @@ -53,7 +53,7 @@ public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellat for (int i = 0; i < _properties.Count; i++) { t = _properties[i].WriteToAsync(writer, cancellationToken, converters); - if (!t.IsCompletedSucessfully()) + if (!t.IsCompletedSuccessfully()) { return AwaitProperties(t, i + 1, writer, cancellationToken, converters); } diff --git a/Src/Newtonsoft.Json/Linq/JObject.cs b/Src/Newtonsoft.Json/Linq/JObject.cs index 371a951ff..872c8ae7c 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.cs @@ -742,7 +742,7 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() return ((ICustomTypeDescriptor)this).GetProperties(null); } - PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) + PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes) { PropertyDescriptor[] propertiesArray = new PropertyDescriptor[Count]; int i = 0; @@ -790,7 +790,7 @@ TypeConverter ICustomTypeDescriptor.GetConverter() return null; } - EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) + EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[]? attributes) { return EventDescriptorCollection.Empty; } @@ -800,7 +800,7 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents() return EventDescriptorCollection.Empty; } - object? ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) + object? ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor? pd) { if (pd is JPropertyDescriptor) { diff --git a/Src/Newtonsoft.Json/Linq/JProperty.Async.cs b/Src/Newtonsoft.Json/Linq/JProperty.Async.cs index dcd7cb3b1..d1e845dce 100644 --- a/Src/Newtonsoft.Json/Linq/JProperty.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JProperty.Async.cs @@ -44,7 +44,7 @@ public partial class JProperty public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { Task task = writer.WritePropertyNameAsync(_name, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return WriteValueAsync(writer, cancellationToken, converters); } diff --git a/Src/Newtonsoft.Json/Linq/JProperty.cs b/Src/Newtonsoft.Json/Linq/JProperty.cs index b59918d89..3c738cf52 100644 --- a/Src/Newtonsoft.Json/Linq/JProperty.cs +++ b/Src/Newtonsoft.Json/Linq/JProperty.cs @@ -353,7 +353,13 @@ public override void WriteTo(JsonWriter writer, params JsonConverter[] converter internal override int GetDeepHashCode() { - return _name.GetHashCode() ^ (Value?.GetDeepHashCode() ?? 0); + int hash; +#if HAVE_GETHASHCODE_STRING_COMPARISON + hash = _name.GetHashCode(StringComparison.Ordinal); +#else + hash = _name.GetHashCode(); +#endif + return hash ^ (Value?.GetDeepHashCode() ?? 0); } /// diff --git a/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs b/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs index 72ea02070..606b2f2db 100644 --- a/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs +++ b/Src/Newtonsoft.Json/Linq/JPropertyDescriptor.cs @@ -67,7 +67,7 @@ public override bool CanResetValue(object component) /// The value of a property for a given component. /// /// The component with the property for which to retrieve the value. - public override object? GetValue(object component) + public override object? GetValue(object? component) { return (component as JObject)?[Name]; } @@ -85,7 +85,7 @@ public override void ResetValue(object component) /// /// The component with the property value that is to be set. /// The new value. - public override void SetValue(object component, object value) + public override void SetValue(object? component, object? value) { if (component is JObject o) { diff --git a/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs b/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs index 1c4c186bc..42a37d8af 100644 --- a/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs +++ b/Src/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs @@ -131,7 +131,7 @@ public bool Remove(string key) if (_dictionary != null) { - return _dictionary.TryGetValue(key, out JToken value) && Remove(value); + return _dictionary.TryGetValue(key, out JToken? value) && Remove(value); } return false; @@ -259,7 +259,7 @@ public bool Compare(JPropertyKeyedCollection other) foreach (KeyValuePair keyAndProperty in d1) { - if (!d2.TryGetValue(keyAndProperty.Key, out JToken secondValue)) + if (!d2.TryGetValue(keyAndProperty.Key, out JToken? secondValue)) { return false; } diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 9cb008ae2..336d748aa 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -1333,7 +1333,7 @@ public static explicit operator ulong(JToken value) if (v.Value is string) { - return Convert.FromBase64String(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return Convert.FromBase64String(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } #if HAVE_BIG_INTEGER if (v.Value is BigInteger integer) @@ -1368,7 +1368,7 @@ public static explicit operator Guid(JToken value) return new Guid(bytes); } - return (v.Value is Guid guid) ? guid : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return (v.Value is Guid guid) ? guid : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } /// @@ -1399,7 +1399,7 @@ public static explicit operator Guid(JToken value) return new Guid(bytes); } - return (v.Value is Guid guid) ? guid : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return (v.Value is Guid guid) ? guid : new Guid(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } /// @@ -1415,7 +1415,7 @@ public static explicit operator TimeSpan(JToken value) throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); } - return (v.Value is TimeSpan span) ? span : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return (v.Value is TimeSpan span) ? span : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } /// @@ -1441,7 +1441,7 @@ public static explicit operator TimeSpan(JToken value) return null; } - return (v.Value is TimeSpan span) ? span : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return (v.Value is TimeSpan span) ? span : ConvertUtils.ParseTimeSpan(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } /// @@ -1467,7 +1467,7 @@ public static explicit operator TimeSpan(JToken value) return null; } - return (v.Value is Uri uri) ? uri : new Uri(Convert.ToString(v.Value, CultureInfo.InvariantCulture)); + return (v.Value is Uri uri) ? uri : new Uri(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!); } #if HAVE_BIG_INTEGER @@ -1957,15 +1957,15 @@ public static JToken FromObject(object o, JsonSerializer jsonSerializer) } catch (Exception ex) { - Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType); + Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType)!; throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string?)this, enumType.Name), ex); } } if (Type == JTokenType.Integer) { - Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType); - return Enum.ToObject(enumType, ((JValue)this).Value); + Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType)!; + return Enum.ToObject(enumType, ((JValue)this).Value!); } } diff --git a/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs b/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs index 2930896d9..8e5314b21 100644 --- a/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs +++ b/Src/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs @@ -40,7 +40,7 @@ public class JTokenEqualityComparer : IEqualityComparer /// /// true if the specified objects are equal; otherwise, false. /// - public bool Equals(JToken x, JToken y) + public bool Equals(JToken? x, JToken? y) { return JToken.DeepEquals(x, y); } diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs index 86ea4dfe6..09ed1fd42 100644 --- a/Src/Newtonsoft.Json/Linq/JValue.cs +++ b/Src/Newtonsoft.Json/Linq/JValue.cs @@ -307,8 +307,8 @@ internal static int Compare(JTokenType valueType, object? objA, object? objB) case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: - string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture); - string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture); + string? s1 = Convert.ToString(objA, CultureInfo.InvariantCulture); + string? s2 = Convert.ToString(objB, CultureInfo.InvariantCulture); return string.CompareOrdinal(s1, s2); case JTokenType.Boolean: @@ -859,7 +859,7 @@ public bool Equals(JValue? other) /// /// true if the specified is equal to the current ; otherwise, false. /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is JValue v) { @@ -902,7 +902,7 @@ public override string ToString() return string.Empty; } - return _value.ToString(); + return _value.ToString()!; } /// @@ -924,7 +924,7 @@ public string ToString(string format) /// /// A that represents this instance. /// - public string ToString(IFormatProvider formatProvider) + public string ToString(IFormatProvider? formatProvider) { return ToString(null, formatProvider); } @@ -937,7 +937,7 @@ public string ToString(IFormatProvider formatProvider) /// /// A that represents this instance. /// - public string ToString(string? format, IFormatProvider formatProvider) + public string ToString(string? format, IFormatProvider? formatProvider) { if (_value == null) { @@ -950,7 +950,7 @@ public string ToString(string? format, IFormatProvider formatProvider) } else { - return _value.ToString(); + return _value.ToString()!; } } @@ -1035,7 +1035,7 @@ public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder b } #endif - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { if (obj == null) { @@ -1078,7 +1078,7 @@ int IComparable.CompareTo(object obj) /// /// is not of the same type as this instance. /// - public int CompareTo(JValue obj) + public int CompareTo(JValue? obj) { if (obj == null) { @@ -1108,79 +1108,79 @@ TypeCode IConvertible.GetTypeCode() return TypeCode.Object; } - bool IConvertible.ToBoolean(IFormatProvider provider) + bool IConvertible.ToBoolean(IFormatProvider? provider) { return (bool)this; } - char IConvertible.ToChar(IFormatProvider provider) + char IConvertible.ToChar(IFormatProvider? provider) { return (char)this; } - sbyte IConvertible.ToSByte(IFormatProvider provider) + sbyte IConvertible.ToSByte(IFormatProvider? provider) { return (sbyte)this; } - byte IConvertible.ToByte(IFormatProvider provider) + byte IConvertible.ToByte(IFormatProvider? provider) { return (byte)this; } - short IConvertible.ToInt16(IFormatProvider provider) + short IConvertible.ToInt16(IFormatProvider? provider) { return (short)this; } - ushort IConvertible.ToUInt16(IFormatProvider provider) + ushort IConvertible.ToUInt16(IFormatProvider? provider) { return (ushort)this; } - int IConvertible.ToInt32(IFormatProvider provider) + int IConvertible.ToInt32(IFormatProvider? provider) { return (int)this; } - uint IConvertible.ToUInt32(IFormatProvider provider) + uint IConvertible.ToUInt32(IFormatProvider? provider) { return (uint)this; } - long IConvertible.ToInt64(IFormatProvider provider) + long IConvertible.ToInt64(IFormatProvider? provider) { return (long)this; } - ulong IConvertible.ToUInt64(IFormatProvider provider) + ulong IConvertible.ToUInt64(IFormatProvider? provider) { return (ulong)this; } - float IConvertible.ToSingle(IFormatProvider provider) + float IConvertible.ToSingle(IFormatProvider? provider) { return (float)this; } - double IConvertible.ToDouble(IFormatProvider provider) + double IConvertible.ToDouble(IFormatProvider? provider) { return (double)this; } - decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider? provider) { return (decimal)this; } - DateTime IConvertible.ToDateTime(IFormatProvider provider) + DateTime IConvertible.ToDateTime(IFormatProvider? provider) { return (DateTime)this; } - object? IConvertible.ToType(Type conversionType, IFormatProvider provider) + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) { - return ToObject(conversionType); + return ToObject(conversionType)!; } #endif } diff --git a/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs b/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs index 1ab970411..617a7c419 100644 --- a/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs +++ b/Src/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs @@ -291,7 +291,7 @@ internal static bool EqualsWithStringCoercion(JValue value, JValue queryValue) break; case JTokenType.Guid: case JTokenType.TimeSpan: - currentValueString = value.Value!.ToString(); + currentValueString = value.Value!.ToString()!; break; case JTokenType.Uri: currentValueString = ((Uri)value.Value!).OriginalString; diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index fd834d77a..21b98b1ee 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -1,6 +1,6 @@  - net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0 + net6.0;net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0 $(LibraryFrameworks) 9.0 @@ -51,8 +51,12 @@ + + Json.NET .NET 6.0 + HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;$(AdditionalConstants) + - Json.NET + Json.NET .NET 4.5 HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CAS;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;$(AdditionalConstants) diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs index 445d3a6f6..b506565db 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs @@ -89,7 +89,10 @@ internal JsonSchema Read(JsonReader reader) private string UnescapeReference(string reference) { - return Uri.UnescapeDataString(reference).Replace("~1", "/").Replace("~0", "~"); + string unescapedReference = Uri.UnescapeDataString(reference); + unescapedReference = StringUtils.Replace(unescapedReference, "~1", "/"); + unescapedReference = StringUtils.Replace(unescapedReference, "~0", "~"); + return unescapedReference; } private JsonSchema ResolveReferences(JsonSchema schema) @@ -220,7 +223,11 @@ private JsonSchema BuildSchema(JToken token) return deferredSchema; } - string location = token.Path.Replace(".", "/").Replace("[", "/").Replace("]", string.Empty); + string location = token.Path; + location = StringUtils.Replace(location, ".", "/"); + location = StringUtils.Replace(location, "[", "/"); + location = StringUtils.Replace(location, "]", string.Empty); + if (!StringUtils.IsNullOrEmpty(location)) { location = "/" + location; diff --git a/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs b/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs index d3fdcf026..554e89a57 100644 --- a/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs @@ -66,7 +66,7 @@ public override JsonContract ResolveContract(Type type) // for backwards compadibility the CamelCasePropertyNamesContractResolver shares contracts between instances StructMultiKey key = new StructMultiKey(GetType(), type); Dictionary, JsonContract>? cache = _contractCache; - if (cache == null || !cache.TryGetValue(key, out JsonContract contract)) + if (cache == null || !cache.TryGetValue(key, out JsonContract? contract)) { contract = CreateContract(type); diff --git a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index 87a781b20..864697f07 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -418,7 +418,7 @@ protected virtual JsonObjectContract CreateObjectContract(Type objectType) } } - MemberInfo extensionDataMember = GetExtensionDataMemberForType(contract.NonNullableUnderlyingType); + MemberInfo? extensionDataMember = GetExtensionDataMemberForType(contract.NonNullableUnderlyingType); if (extensionDataMember != null) { SetExtensionDataDelegates(contract, extensionDataMember); @@ -439,7 +439,7 @@ private static void ThrowUnableToSerializeError(object o, StreamingContext conte throw new JsonSerializationException("Unable to serialize instance of '{0}'.".FormatWith(CultureInfo.InvariantCulture, o.GetType())); } - private MemberInfo GetExtensionDataMemberForType(Type type) + private MemberInfo? GetExtensionDataMemberForType(Type type) { IEnumerable members = GetClassHierarchyForType(type).SelectMany(baseType => { @@ -450,7 +450,7 @@ private MemberInfo GetExtensionDataMemberForType(Type type) return m; }); - MemberInfo extensionDataMember = members.LastOrDefault(m => + MemberInfo? extensionDataMember = members.LastOrDefault(m => { MemberTypes memberType = m.MemberType(); if (memberType != MemberTypes.Property && memberType != MemberTypes.Field) @@ -466,7 +466,7 @@ private MemberInfo GetExtensionDataMemberForType(Type type) if (!ReflectionUtils.CanReadMemberValue(m, true)) { - throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' must have a getter.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name)); + throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' must have a getter.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType!), m.Name)); } Type t = ReflectionUtils.GetMemberUnderlyingType(m); @@ -482,7 +482,7 @@ private MemberInfo GetExtensionDataMemberForType(Type type) } } - throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType), m.Name)); + throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(m.DeclaringType!), m.Name)); }); return extensionDataMember; @@ -640,7 +640,7 @@ IEnumerator IEnumerable.GetEnumerator() { foreach (ParameterInfo parameterInfo in parameters) { - JsonProperty? memberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); + JsonProperty? memberProperty = MatchProperty(memberProperties, parameterInfo.Name!, parameterInfo.ParameterType); if (memberProperty == null || memberProperty.Writable) { return null; @@ -688,7 +688,7 @@ protected virtual IList CreateConstructorParameters(ConstructorInf { ParameterInfo[] constructorParameters = constructor.GetParameters(); - JsonPropertyCollection parameterCollection = new JsonPropertyCollection(constructor.DeclaringType); + JsonPropertyCollection parameterCollection = new JsonPropertyCollection(constructor.DeclaringType!); foreach (ParameterInfo parameterInfo in constructorParameters) { @@ -746,7 +746,7 @@ protected virtual JsonProperty CreatePropertyFromConstructorParameter(JsonProper property.PropertyType = parameterInfo.ParameterType; property.AttributeProvider = new ReflectionAttributeProvider(parameterInfo); - SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name, parameterInfo.Member.DeclaringType, MemberSerialization.OptOut, out _); + SetPropertySettingsFromAttributes(property, parameterInfo, parameterInfo.Name!, parameterInfo.Member.DeclaringType!, MemberSerialization.OptOut, out _); property.Readable = false; property.Writable = true; @@ -989,7 +989,7 @@ private List GetClassHierarchyForType(Type type) { List ret = new List(); - Type current = type; + Type? current = type; while (current != null && current != typeof(object)) { ret.Add(current); @@ -1127,7 +1127,7 @@ protected virtual JsonISerializableContract CreateISerializableContract(Type obj if (contract.IsInstantiable) { - ConstructorInfo constructorInfo = contract.NonNullableUnderlyingType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] {typeof(SerializationInfo), typeof(StreamingContext)}, null); + ConstructorInfo? constructorInfo = contract.NonNullableUnderlyingType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] {typeof(SerializationInfo), typeof(StreamingContext)}, null); if (constructorInfo != null) { ObjectConstructor creator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructorInfo); @@ -1304,36 +1304,36 @@ private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameter if (currentCallback != null) { - throw new JsonException("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType)); + throw new JsonException("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType!), attributeType)); } if (prevAttributeType != null) { - throw new JsonException("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method)); + throw new JsonException("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType!), method)); } if (method.IsVirtual) { - throw new JsonException("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType)); + throw new JsonException("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType!), attributeType)); } if (method.ReturnType != typeof(void)) { - throw new JsonException("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method)); + throw new JsonException("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType!), method)); } if (attributeType == typeof(OnErrorAttribute)) { if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext)) { - throw new JsonException("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext), typeof(ErrorContext))); + throw new JsonException("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType!), method, typeof(StreamingContext), typeof(ErrorContext))); } } else { if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext)) { - throw new JsonException("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext))); + throw new JsonException("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType!), method, typeof(StreamingContext))); } } @@ -1346,7 +1346,7 @@ internal static string GetClrTypeFullName(Type type) { if (type.IsGenericTypeDefinition() || !type.ContainsGenericParameters()) { - return type.FullName; + return type.FullName!; } return "{0}.{1}".FormatWith(CultureInfo.InvariantCulture, type.Namespace, type.Name); @@ -1437,7 +1437,7 @@ protected virtual JsonProperty CreateProperty(MemberInfo member, MemberSerializa property.ValueProvider = CreateMemberValueProvider(member); property.AttributeProvider = new ReflectionAttributeProvider(member); - SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType, memberSerialization, out bool allowNonPublicAccess); + SetPropertySettingsFromAttributes(property, member, member.Name, member.DeclaringType!, memberSerialization, out bool allowNonPublicAccess); if (memberSerialization != MemberSerialization.Fields) { @@ -1635,7 +1635,7 @@ private void SetPropertySettingsFromAttributes(JsonProperty property, object att private Predicate? CreateShouldSerializeTest(MemberInfo member) { - MethodInfo shouldSerializeMethod = member.DeclaringType.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, ReflectionUtils.EmptyTypes); + MethodInfo? shouldSerializeMethod = member.DeclaringType!.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, ReflectionUtils.EmptyTypes); if (shouldSerializeMethod == null || shouldSerializeMethod.ReturnType != typeof(bool)) { @@ -1650,7 +1650,7 @@ private void SetPropertySettingsFromAttributes(JsonProperty property, object att private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess) { - MemberInfo? specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + MemberInfo? specifiedMember = member.DeclaringType!.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (specifiedMember == null) { specifiedMember = member.DeclaringType.GetField(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); diff --git a/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs index 83e0f4846..e33dc58b1 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs @@ -52,15 +52,15 @@ private BidirectionalDictionary GetMappings(object context) public object ResolveReference(object context, string reference) { - GetMappings(context).TryGetByFirst(reference, out object value); - return value; + GetMappings(context).TryGetByFirst(reference, out object? value); + return value!; } public string GetReference(object context, object value) { BidirectionalDictionary mappings = GetMappings(context); - if (!mappings.TryGetBySecond(value, out string reference)) + if (!mappings.TryGetBySecond(value, out string? reference)) { _referenceCount++; reference = _referenceCount.ToString(CultureInfo.InvariantCulture); diff --git a/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs b/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs index 1adf55a62..37d25cf26 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs @@ -60,7 +60,7 @@ private Type GetTypeFromTypeNameKey(StructMultiKey typeNameKey) if (assemblyName != null) { - Assembly assembly; + Assembly? assembly; #if !(DOTNET || PORTABLE40 || PORTABLE) // look, I don't like using obsolete methods as much as you do but this is the only way @@ -101,7 +101,7 @@ private Type GetTypeFromTypeNameKey(StructMultiKey typeNameKey) { // if generic type, try manually parsing the type arguments for the case of dynamically loaded assemblies // example generic typeName format: System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] - if (typeName.IndexOf('`') >= 0) + if (StringUtils.IndexOf(typeName, '`') >= 0) { try { @@ -123,18 +123,18 @@ private Type GetTypeFromTypeNameKey(StructMultiKey typeNameKey) } else { - return Type.GetType(typeName); + return Type.GetType(typeName)!; } } private Type? GetGenericTypeFromTypeName(string typeName, Assembly assembly) { Type? type = null; - int openBracketIndex = typeName.IndexOf('['); + int openBracketIndex = StringUtils.IndexOf(typeName, '['); if (openBracketIndex >= 0) { string genericTypeDefName = typeName.Substring(0, openBracketIndex); - Type genericTypeDef = assembly.GetType(genericTypeDefName); + Type? genericTypeDef = assembly.GetType(genericTypeDefName); if (genericTypeDef != null) { List genericTypeArguments = new List(); diff --git a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs index a2ce9dac8..87c409e6d 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs @@ -127,7 +127,7 @@ public JsonArrayContract(Type underlyingType) Type? tempCollectionType; if (IsArray) { - CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); + CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType)!; IsReadOnlyOrFixedSize = true; _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); @@ -274,6 +274,7 @@ internal IWrappedCollection CreateWrapper(object list) if (_genericWrapperCreator == null) { MiscellaneousUtils.Assert(_genericCollectionDefinitionType != null); + MiscellaneousUtils.Assert(CollectionItemType != null); _genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType); @@ -289,7 +290,7 @@ internal IWrappedCollection CreateWrapper(object list) constructorArgument = _genericCollectionDefinitionType; } - ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument }); + ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument })!; _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } diff --git a/Src/Newtonsoft.Json/Serialization/JsonContract.cs b/Src/Newtonsoft.Json/Serialization/JsonContract.cs index c77470291..d4f802cb9 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonContract.cs @@ -248,7 +248,7 @@ internal JsonContract(Type underlyingType) IsNullable = ReflectionUtils.IsNullable(underlyingType); - NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; + NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType)! : underlyingType; _createdType = CreatedType = NonNullableUnderlyingType; diff --git a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs index 6c5afbe10..25828d13b 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs @@ -223,9 +223,9 @@ internal IWrappedDictionary CreateWrapper(object dictionary) { if (_genericWrapperCreator == null) { - _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType); + _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType!, DictionaryValueType!); - ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType! }); + ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType! })!; _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } diff --git a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs index 46992bc67..408a02975 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs @@ -53,10 +53,10 @@ private T GetTokenValue(object value) ValidationUtils.ArgumentNotNull(value, nameof(value)); JValue v = (JValue)value; - return (T)System.Convert.ChangeType(v.Value, typeof(T), CultureInfo.InvariantCulture); + return (T)System.Convert.ChangeType(v.Value, typeof(T), CultureInfo.InvariantCulture)!; } - public object? Convert(object value, Type type) + public object Convert(object value, Type type) { ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -65,7 +65,7 @@ private T GetTokenValue(object value) throw new ArgumentException("Value is not a JToken.", nameof(value)); } - return _reader.CreateISerializableItem(token, type, _contract, _member); + return _reader.CreateISerializableItem(token, type, _contract, _member)!; } public object Convert(object value, TypeCode typeCode) @@ -74,7 +74,7 @@ public object Convert(object value, TypeCode typeCode) object? resolvedValue = (value is JValue v) ? v.Value : value; - return System.Convert.ChangeType(resolvedValue, typeCode, CultureInfo.InvariantCulture); + return System.Convert.ChangeType(resolvedValue, typeCode, CultureInfo.InvariantCulture)!; } public bool ToBoolean(object value) diff --git a/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs b/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs index 8b3d201cb..684be0d3b 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs @@ -145,7 +145,7 @@ public void AddProperty(JsonProperty property) return property; } - private bool TryGetValue(string key, [NotNullWhen(true)]out JsonProperty? item) + private bool TryGetProperty(string key, [NotNullWhen(true)]out JsonProperty? item) { if (Dictionary == null) { @@ -167,7 +167,7 @@ private bool TryGetValue(string key, [NotNullWhen(true)]out JsonProperty? item) // KeyedCollection has an ordinal comparer if (comparisonType == StringComparison.Ordinal) { - if (TryGetValue(propertyName, out JsonProperty? property)) + if (TryGetProperty(propertyName, out JsonProperty? property)) { return property; } diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs index 8e76dc0f7..1cdb0c5ae 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs @@ -35,7 +35,7 @@ internal abstract class JsonSerializerInternalBase { private class ReferenceEqualsEqualityComparer : IEqualityComparer { - bool IEqualityComparer.Equals(object x, object y) + bool IEqualityComparer.Equals(object? x, object? y) { return ReferenceEquals(x, y); } diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index df77f51ff..4ef652b6b 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -332,7 +332,7 @@ private JToken CreateJObject(JsonReader reader) return EnsureType(reader, s, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.StartConstructor: - string constructorName = reader.Value!.ToString(); + string constructorName = reader.Value!.ToString()!; return EnsureType(reader, constructorName, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.Null: @@ -692,7 +692,7 @@ private bool ReadMetadataProperties(JsonReader reader, ref Type? objectType, ref if (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (propertyName.Length > 0 && propertyName[0] == '$') { @@ -702,7 +702,7 @@ private bool ReadMetadataProperties(JsonReader reader, ref Type? objectType, ref do { - propertyName = reader.Value!.ToString(); + propertyName = reader.Value!.ToString()!; if (string.Equals(propertyName, JsonTypeReflector.RefPropertyName, StringComparison.Ordinal)) { @@ -740,7 +740,7 @@ private bool ReadMetadataProperties(JsonReader reader, ref Type? objectType, ref else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); - string qualifiedTypeName = reader.Value!.ToString(); + string qualifiedTypeName = reader.Value!.ToString()!; ResolveTypeName(reader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName); @@ -898,7 +898,7 @@ private JsonArrayContract EnsureArrayContract(JsonReader reader, Type objectType } else if (arrayContract.IsArray) { - Array a = Array.CreateInstance(arrayContract.CollectionItemType, list.Count); + Array a = Array.CreateInstance(arrayContract.CollectionItemType!, list.Count); list.CopyTo(a, 0); list = a; } @@ -975,7 +975,7 @@ private bool HasNoDefinedType(JsonContract? contract) } if (ConvertUtils.IsInteger(primitiveContract.TypeCode)) { - return Enum.ToObject(contract.NonNullableUnderlyingType, value); + return Enum.ToObject(contract.NonNullableUnderlyingType, value!); } } else if (contract.NonNullableUnderlyingType == typeof(DateTime)) @@ -1384,7 +1384,7 @@ private object PopulateDictionary(IDictionary dictionary, JsonReader reader, Jso { case JsonToken.PropertyName: object keyValue = reader.Value!; - if (CheckPropertyName(reader, keyValue.ToString())) + if (CheckPropertyName(reader, keyValue.ToString()!)) { continue; } @@ -1399,7 +1399,7 @@ private object PopulateDictionary(IDictionary dictionary, JsonReader reader, Jso case PrimitiveTypeCode.DateTime: case PrimitiveTypeCode.DateTimeNullable: { - keyValue = DateTimeUtils.TryParseDateTime(keyValue.ToString(), reader.DateTimeZoneHandling, reader.DateFormatString, reader.Culture, out DateTime dt) + keyValue = DateTimeUtils.TryParseDateTime(keyValue.ToString()!, reader.DateTimeZoneHandling, reader.DateFormatString, reader.Culture, out DateTime dt) ? dt : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; break; @@ -1408,7 +1408,7 @@ private object PopulateDictionary(IDictionary dictionary, JsonReader reader, Jso case PrimitiveTypeCode.DateTimeOffset: case PrimitiveTypeCode.DateTimeOffsetNullable: { - keyValue = DateTimeUtils.TryParseDateTimeOffset(keyValue.ToString(), reader.DateFormatString, reader.Culture, out DateTimeOffset dt) + keyValue = DateTimeUtils.TryParseDateTimeOffset(keyValue.ToString()!, reader.DateFormatString, reader.Culture, out DateTimeOffset dt) ? dt : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; break; @@ -1416,7 +1416,7 @@ private object PopulateDictionary(IDictionary dictionary, JsonReader reader, Jso #endif default: keyValue = contract.KeyContract != null && contract.KeyContract.IsEnum - ? EnumUtils.ParseEnum(contract.KeyContract.NonNullableUnderlyingType, (Serializer._contractResolver as DefaultContractResolver)?.NamingStrategy, keyValue.ToString(), false) + ? EnumUtils.ParseEnum(contract.KeyContract.NonNullableUnderlyingType, (Serializer._contractResolver as DefaultContractResolver)?.NamingStrategy, keyValue.ToString()!, false) : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; break; } @@ -1752,7 +1752,7 @@ private object CreateISerializable(JsonReader reader, JsonISerializableContract switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value!.ToString(); + string memberName = reader.Value!.ToString()!; if (!reader.Read()) { throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); @@ -1855,7 +1855,7 @@ private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, Js switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value!.ToString(); + string memberName = reader.Value!.ToString()!; try { @@ -2207,7 +2207,7 @@ private List ResolvePropertyAndCreatorValues(JsonObjectC switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value!.ToString(); + string memberName = reader.Value!.ToString()!; CreatorPropertyContext creatorPropertyContext = new CreatorPropertyContext(memberName) { @@ -2356,7 +2356,7 @@ private object PopulateObject(object newObject, JsonReader reader, JsonObjectCon { case JsonToken.PropertyName: { - string propertyName = reader.Value!.ToString(); + string propertyName = reader.Value!.ToString()!; if (CheckPropertyName(reader, propertyName)) { diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs index 675b5fede..4ea158381 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs @@ -399,7 +399,7 @@ internal static bool TryConvertToString(object value, Type type, [NotNullWhen(tr #if HAVE_TYPE_DESCRIPTOR if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out TypeConverter converter)) { - s = converter.ConvertToInvariantString(value); + s = converter.ConvertToInvariantString(value)!; return true; } #endif @@ -414,7 +414,7 @@ internal static bool TryConvertToString(object value, Type type, [NotNullWhen(tr if (value is Type t) { - s = t.AssemblyQualifiedName; + s = t.AssemblyQualifiedName!; return true; } @@ -778,7 +778,7 @@ private void SerializeMultidimensionalArray(JsonWriter writer, Array values, Jso if (isTopLevel) { - object value = values.GetValue(newIndices); + object value = values.GetValue(newIndices)!; try { @@ -879,7 +879,7 @@ private void SerializeISerializable(JsonWriter writer, ISerializable value, Json if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member)) { writer.WritePropertyName(serializationEntry.Name); - WriteReference(writer, serializationEntry.Value); + WriteReference(writer, serializationEntry.Value!); } else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member)) { @@ -1176,7 +1176,7 @@ private string GetPropertyName(JsonWriter writer, object name, JsonContract cont return enumName; } - return Convert.ToString(name, CultureInfo.InvariantCulture); + return Convert.ToString(name, CultureInfo.InvariantCulture)!; } } } @@ -1188,7 +1188,7 @@ private string GetPropertyName(JsonWriter writer, object name, JsonContract cont else { escape = true; - return name.ToString(); + return name.ToString()!; } } diff --git a/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs b/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs index 28783b4ce..da8430071 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs @@ -33,6 +33,7 @@ using System.Security.Permissions; #endif using Newtonsoft.Json.Utilities; +using System.Runtime.CompilerServices; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else @@ -99,7 +100,7 @@ public static bool CanTypeDescriptorConvertString(Type type, out TypeConverter t public static DataContractAttribute? GetDataContractAttribute(Type type) { // DataContractAttribute does not have inheritance - Type currentType = type; + Type? currentType = type; while (currentType != null) { @@ -132,11 +133,11 @@ public static bool CanTypeDescriptorConvertString(Type type, out TypeConverter t { if (propertyInfo.IsVirtual()) { - Type currentType = propertyInfo.DeclaringType; + Type? currentType = propertyInfo.DeclaringType; while (result == null && currentType != null) { - PropertyInfo baseProperty = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(currentType, propertyInfo); + PropertyInfo? baseProperty = (PropertyInfo?)ReflectionUtils.GetMemberInfoFromType(currentType, propertyInfo); if (baseProperty != null && baseProperty.IsVirtual()) { result = CachedAttributeGetter.GetAttribute(baseProperty); @@ -248,7 +249,7 @@ public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyTyp return param.GetType(); }).ToArray(); - ConstructorInfo parameterizedConstructorInfo = type.GetConstructor(paramTypes); + ConstructorInfo? parameterizedConstructorInfo = type.GetConstructor(paramTypes); if (parameterizedConstructorInfo != null) { @@ -347,10 +348,10 @@ public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyTyp T? attribute; #if !(NET20 || DOTNET) - Type? metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType); + Type? metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType!); if (metadataType != null) { - MemberInfo metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo); + MemberInfo? metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo); if (metadataTypeMemberInfo != null) { @@ -373,7 +374,7 @@ public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyTyp { foreach (Type typeInterface in memberInfo.DeclaringType.GetInterfaces()) { - MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo); + MemberInfo? interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo); if (interfaceTypeMemberInfo != null) { @@ -459,7 +460,9 @@ public static bool DynamicCodeGeneration { if (_dynamicCodeGeneration == null) { -#if HAVE_CAS +#if HAVE_DYNAMIC_CODE_COMPILED + _dynamicCodeGeneration = RuntimeFeature.IsDynamicCodeCompiled; +#elif HAVE_CAS try { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); diff --git a/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs b/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs index 88118844f..7412531e9 100644 --- a/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs +++ b/Src/Newtonsoft.Json/Serialization/NamingStrategy.cs @@ -123,7 +123,7 @@ public override int GetHashCode() /// /// /// - public override bool Equals(object obj) => Equals(obj as NamingStrategy); + public override bool Equals(object? obj) => Equals(obj as NamingStrategy); /// /// Compare to another NamingStrategy diff --git a/Src/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs b/Src/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs index 6a960a3d6..e5465af80 100644 --- a/Src/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs +++ b/Src/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs @@ -43,7 +43,7 @@ public SerializationBinderAdapter(SerializationBinder serializationBinder) public Type BindToType(string? assemblyName, string typeName) { - return SerializationBinder.BindToType(assemblyName, typeName); + return SerializationBinder.BindToType(assemblyName!, typeName)!; } public void BindToName(Type serializedType, out string? assemblyName, out string? typeName) diff --git a/Src/Newtonsoft.Json/Utilities/AsyncUtils.cs b/Src/Newtonsoft.Json/Utilities/AsyncUtils.cs index e863e735b..578b37de7 100644 --- a/Src/Newtonsoft.Json/Utilities/AsyncUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/AsyncUtils.cs @@ -95,11 +95,11 @@ public static Task ReadAsync(this TextReader reader, char[] buffer, int ind return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : reader.ReadAsync(buffer, index, count); } - public static bool IsCompletedSucessfully(this Task task) + public static bool IsCompletedSuccessfully(this Task task) { // IsCompletedSucessfully is the faster method, but only currently exposed on .NET Core 2.0 -#if NETCOREAPP2_0 - return task.IsCompletedSucessfully; +#if NETCOREAPP2_0_OR_GREATER + return task.IsCompletedSuccessfully; #else return task.Status == TaskStatus.RanToCompletion; #endif diff --git a/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs b/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs index c1dd16d11..887ee7f0c 100644 --- a/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs +++ b/Src/Newtonsoft.Json/Utilities/Base64Encoder.cs @@ -78,12 +78,12 @@ public void Encode(byte[] buffer, int index, int count) if (_leftOverBytesCount > 0) { - if(FulfillFromLeftover(buffer, index, ref count)) + if (FulfillFromLeftover(buffer, index, ref count)) { return; } - int num2 = Convert.ToBase64CharArray(_leftOverBytes, 0, 3, _charsLine, 0); + int num2 = Convert.ToBase64CharArray(_leftOverBytes!, 0, 3, _charsLine, 0); WriteChars(_charsLine, 0, num2); } @@ -145,7 +145,7 @@ public void Flush() { if (_leftOverBytesCount > 0) { - int count = Convert.ToBase64CharArray(_leftOverBytes, 0, _leftOverBytesCount, _charsLine, 0); + int count = Convert.ToBase64CharArray(_leftOverBytes!, 0, _leftOverBytesCount, _charsLine, 0); WriteChars(_charsLine, 0, count); _leftOverBytesCount = 0; } @@ -169,7 +169,7 @@ public async Task EncodeAsync(byte[] buffer, int index, int count, CancellationT return; } - int num2 = Convert.ToBase64CharArray(_leftOverBytes, 0, 3, _charsLine, 0); + int num2 = Convert.ToBase64CharArray(_leftOverBytes!, 0, 3, _charsLine, 0); await WriteCharsAsync(_charsLine, 0, num2, cancellationToken).ConfigureAwait(false); } @@ -203,7 +203,7 @@ public Task FlushAsync(CancellationToken cancellationToken) if (_leftOverBytesCount > 0) { - int count = Convert.ToBase64CharArray(_leftOverBytes, 0, _leftOverBytesCount, _charsLine, 0); + int count = Convert.ToBase64CharArray(_leftOverBytes!, 0, _leftOverBytesCount, _charsLine, 0); _leftOverBytesCount = 0; return WriteCharsAsync(_charsLine, 0, count, cancellationToken); } diff --git a/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs b/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs index 2f97c0b95..7ed826d36 100644 --- a/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs +++ b/Src/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs @@ -25,11 +25,14 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace Newtonsoft.Json.Utilities { internal class BidirectionalDictionary + where TFirst : notnull + where TSecond : notnull { private readonly IDictionary _firstToSecond; private readonly IDictionary _secondToFirst; @@ -61,7 +64,7 @@ public BidirectionalDictionary(IEqualityComparer firstEqualityComparer, public void Set(TFirst first, TSecond second) { - if (_firstToSecond.TryGetValue(first, out TSecond existingSecond)) + if (_firstToSecond.TryGetValue(first, out TSecond? existingSecond)) { if (!existingSecond!.Equals(second)) { @@ -69,7 +72,7 @@ public void Set(TFirst first, TSecond second) } } - if (_secondToFirst.TryGetValue(second, out TFirst existingFirst)) + if (_secondToFirst.TryGetValue(second, out TFirst? existingFirst)) { if (!existingFirst!.Equals(first)) { @@ -81,12 +84,12 @@ public void Set(TFirst first, TSecond second) _secondToFirst.Add(second, first); } - public bool TryGetByFirst(TFirst first, out TSecond second) + public bool TryGetByFirst(TFirst first, [NotNullWhen(true)] out TSecond? second) { return _firstToSecond.TryGetValue(first, out second); } - public bool TryGetBySecond(TSecond second, out TFirst first) + public bool TryGetBySecond(TSecond second, [NotNullWhen(true)] out TFirst? first) { return _secondToFirst.TryGetValue(second, out first); } diff --git a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs index 85826a556..8b0a0125d 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs @@ -289,7 +289,7 @@ private static IList GetDimensions(IList values, int dimensionsCount) break; } - object v = currentArray[0]; + object? v = currentArray[0]; if (v is IList list) { currentArray = list; @@ -341,11 +341,11 @@ private static object JaggedArrayGetValue(IList values, int[] indices) int index = indices[i]; if (i == indices.Length - 1) { - return currentList[index]; + return currentList[index]!; } else { - currentList = (IList)currentList[index]; + currentList = (IList)currentList[index]!; } } return currentList; @@ -368,15 +368,21 @@ public static Array ToMultidimensionalArray(IList values, Type type, int rank) public static T[] ArrayEmpty() { +#if !HAS_ARRAY_EMPTY // Enumerable.Empty no longer returns an empty array in .NET Core 3.0 return EmptyArrayContainer.Empty; +#else + return Array.Empty(); +#endif } +#if !HAS_ARRAY_EMPTY private static class EmptyArrayContainer { #pragma warning disable CA1825 // Avoid zero-length array allocations. public static readonly T[] Empty = new T[0]; #pragma warning restore CA1825 // Avoid zero-length array allocations. } +#endif } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs index ebb79f235..482dad0cd 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs @@ -168,7 +168,7 @@ public virtual bool Remove(T item) public virtual IEnumerator GetEnumerator() { - return (_genericCollection ?? _list.Cast()).GetEnumerator(); + return (_genericCollection ?? _list!.Cast()).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() @@ -176,25 +176,25 @@ IEnumerator IEnumerable.GetEnumerator() return ((IEnumerable)_genericCollection! ?? _list!).GetEnumerator(); } - int IList.Add(object value) + int IList.Add(object? value) { VerifyValueType(value); - Add((T)value); + Add((T)value!); return (Count - 1); } - bool IList.Contains(object value) + bool IList.Contains(object? value) { if (IsCompatibleObject(value)) { - return Contains((T)value); + return Contains((T)value!); } return false; } - int IList.IndexOf(object value) + int IList.IndexOf(object? value) { if (_genericCollection != null) { @@ -203,7 +203,7 @@ int IList.IndexOf(object value) if (IsCompatibleObject(value)) { - return _list!.IndexOf((T)value); + return _list!.IndexOf((T)value!); } return -1; @@ -219,7 +219,7 @@ void IList.RemoveAt(int index) _list!.RemoveAt(index); } - void IList.Insert(int index, object value) + void IList.Insert(int index, object? value) { if (_genericCollection != null) { @@ -227,7 +227,7 @@ void IList.Insert(int index, object value) } VerifyValueType(value); - _list!.Insert(index, (T)value); + _list!.Insert(index, (T)value!); } bool IList.IsFixedSize @@ -246,15 +246,15 @@ bool IList.IsFixedSize } } - void IList.Remove(object value) + void IList.Remove(object? value) { if (IsCompatibleObject(value)) { - Remove((T)value); + Remove((T)value!); } } - object IList.this[int index] + object? IList.this[int index] { get { @@ -273,7 +273,7 @@ object IList.this[int index] } VerifyValueType(value); - _list![index] = (T)value; + _list![index] = (T?)value; } } @@ -297,7 +297,7 @@ object ICollection.SyncRoot } } - private static void VerifyValueType(object value) + private static void VerifyValueType(object? value) { if (!IsCompatibleObject(value)) { @@ -305,7 +305,7 @@ private static void VerifyValueType(object value) } } - private static bool IsCompatibleObject(object value) + private static bool IsCompatibleObject(object? value) { if (!(value is T) && (value != null || (typeof(T).IsValueType() && !ReflectionUtils.IsNullableType(typeof(T))))) { diff --git a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs index 364088e28..9ce44964e 100644 --- a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -215,7 +215,7 @@ public static PrimitiveTypeCode GetTypeCode(Type t, out bool isEnum) // performance? if (ReflectionUtils.IsNullableType(t)) { - Type nonNullable = Nullable.GetUnderlyingType(t); + Type nonNullable = Nullable.GetUnderlyingType(t)!; if (nonNullable.IsEnum()) { Type nullableUnderlyingType = typeof(Nullable<>).MakeGenericType(Enum.GetUnderlyingType(nonNullable)); @@ -263,7 +263,7 @@ public static TimeSpan ParseTimeSpan(string input) { Type initialType = t.Value1; Type targetType = t.Value2; - MethodInfo castMethodInfo = targetType.GetMethod("op_Implicit", new[] { initialType }) + MethodInfo? castMethodInfo = targetType.GetMethod("op_Implicit", new[] { initialType }) ?? targetType.GetMethod("op_Explicit", new[] { initialType }); if (castMethodInfo == null) @@ -414,7 +414,7 @@ private static ConvertResult TryConvertInternal(object? initialValue, CultureInf if (ReflectionUtils.IsNullableType(targetType)) { - targetType = Nullable.GetUnderlyingType(targetType); + targetType = Nullable.GetUnderlyingType(targetType)!; } Type initialType = initialValue.GetType(); @@ -432,7 +432,7 @@ private static ConvertResult TryConvertInternal(object? initialValue, CultureInf { if (initialValue is string) { - value = Enum.Parse(targetType, initialValue.ToString(), true); + value = Enum.Parse(targetType, initialValue.ToString()!, true); return ConvertResult.Success; } else if (IsInteger(initialValue)) diff --git a/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs b/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs index a92e2639b..cf769393c 100644 --- a/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/DictionaryWrapper.cs @@ -89,7 +89,7 @@ public void Add(TKey key, TValue value) { if (_dictionary != null) { - _dictionary.Add(key, value); + _dictionary.Add(key!, value); } else if (_genericDictionary != null) { @@ -105,7 +105,7 @@ public bool ContainsKey(TKey key) { if (_dictionary != null) { - return _dictionary.Contains(key); + return _dictionary.Contains(key!); } #if HAVE_READ_ONLY_COLLECTIONS else if (_readOnlyDictionary != null) @@ -144,9 +144,9 @@ public bool Remove(TKey key) { if (_dictionary != null) { - if (_dictionary.Contains(key)) + if (_dictionary.Contains(key!)) { - _dictionary.Remove(key); + _dictionary.Remove(key!); return true; } else @@ -172,7 +172,7 @@ public bool TryGetValue(TKey key, out TValue? value) { if (_dictionary != null) { - if (!_dictionary.Contains(key)) + if (!_dictionary.Contains(key!)) { #pragma warning disable CS8653 // A default expression introduces a null value for a type parameter. value = default; @@ -181,7 +181,7 @@ public bool TryGetValue(TKey key, out TValue? value) } else { - value = (TValue)_dictionary[key]; + value = (TValue)_dictionary[key!]!; return true; } } @@ -224,7 +224,7 @@ public TValue this[TKey key] { if (_dictionary != null) { - return (TValue)_dictionary[key]; + return (TValue)_dictionary[key!]!; } #if HAVE_READ_ONLY_COLLECTIONS else if (_readOnlyDictionary != null) @@ -241,7 +241,7 @@ public TValue this[TKey key] { if (_dictionary != null) { - _dictionary[key] = value; + _dictionary[key!] = value; } #if HAVE_READ_ONLY_COLLECTIONS else if (_readOnlyDictionary != null) @@ -321,7 +321,7 @@ public void CopyTo(KeyValuePair[] array, int arrayIndex) while (e.MoveNext()) { DictionaryEntry entry = e.Entry; - array[arrayIndex++] = new KeyValuePair((TKey)entry.Key, (TValue)entry.Value); + array[arrayIndex++] = new KeyValuePair((TKey)entry.Key, (TValue)entry.Value!); } } finally @@ -387,13 +387,13 @@ public bool Remove(KeyValuePair item) { if (_dictionary != null) { - if (_dictionary.Contains(item.Key)) + if (_dictionary.Contains(item.Key!)) { - object value = _dictionary[item.Key]; + object? value = _dictionary[item.Key!]; if (Equals(value, item.Value)) { - _dictionary.Remove(item.Key); + _dictionary.Remove(item.Key!); return true; } else @@ -422,7 +422,7 @@ public IEnumerator> GetEnumerator() { if (_dictionary != null) { - return _dictionary.Cast().Select(de => new KeyValuePair((TKey)de.Key, (TValue)de.Value)).GetEnumerator(); + return _dictionary.Cast().Select(de => new KeyValuePair((TKey)de.Key, (TValue)de.Value!)).GetEnumerator(); } #if HAVE_READ_ONLY_COLLECTIONS else if (_readOnlyDictionary != null) @@ -441,7 +441,7 @@ IEnumerator IEnumerable.GetEnumerator() return GetEnumerator(); } - void IDictionary.Add(object key, object value) + void IDictionary.Add(object key, object? value) { if (_dictionary != null) { @@ -455,7 +455,7 @@ void IDictionary.Add(object key, object value) #endif else { - GenericDictionary.Add((TKey)key, (TValue)value); + GenericDictionary.Add((TKey)key, (TValue)value!); } } @@ -517,9 +517,9 @@ public DictionaryEnumerator(IEnumerator Entry.Key; - public object Value => Entry.Value; + public object? Value => Entry.Value; - public object Current => new DictionaryEntry(_e.Current.Key, _e.Current.Value); + public object Current => new DictionaryEntry(_e.Current.Key!, _e.Current.Value); public bool MoveNext() { diff --git a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs index 41286c310..a00cc2ced 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs @@ -37,7 +37,7 @@ internal sealed class DynamicProxyMetaObject : DynamicMetaObject private readonly DynamicProxy _proxy; internal DynamicProxyMetaObject(Expression expression, T value, DynamicProxy proxy) - : base(expression, BindingRestrictions.Empty, value) + : base(expression, BindingRestrictions.Empty, value!) { _proxy = proxy; } @@ -109,7 +109,7 @@ public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, Dy new GetBinderAdapter(binder), NoArgs, fallback(null), - e => binder.FallbackInvoke(e, args, null) + e => binder.FallbackInvoke(e!, args, null) ), null ); @@ -197,7 +197,7 @@ private static ConstantExpression Constant(DynamicMetaObjectBinder binder) Type t = binder.GetType(); while (!t.IsVisible()) { - t = t.BaseType(); + t = t.BaseType()!; } return Expression.Constant(binder, t); } @@ -256,7 +256,7 @@ private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMe Expression.Condition( Expression.Call( Expression.Constant(_proxy), - typeof(DynamicProxy).GetMethod(methodName), + typeof(DynamicProxy).GetMethod(methodName)!, callArgs ), resultMetaObject.Expression, @@ -304,7 +304,7 @@ private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObj Expression.Condition( Expression.Call( Expression.Constant(_proxy), - typeof(DynamicProxy).GetMethod(methodName), + typeof(DynamicProxy).GetMethod(methodName)!, callArgs ), result, @@ -342,7 +342,7 @@ private DynamicMetaObject CallMethodNoResult(string methodName, DynamicMetaObjec Expression.Condition( Expression.Call( Expression.Constant(_proxy), - typeof(DynamicProxy).GetMethod(methodName), + typeof(DynamicProxy).GetMethod(methodName)!, callArgs ), Expression.Empty(), @@ -366,7 +366,7 @@ private BindingRestrictions GetRestrictions() public override IEnumerable GetDynamicMemberNames() { - return _proxy.GetDynamicMemberNames((T)Value); + return _proxy.GetDynamicMemberNames((T)Value!); } // It is okay to throw NotSupported from this binder. This object @@ -380,7 +380,7 @@ internal GetBinderAdapter(InvokeMemberBinder binder) : { } - public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) + public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject? errorSuggestion) { throw new NotSupportedException(); } diff --git a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs index e899c4c31..10b4acb3b 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs @@ -51,7 +51,7 @@ private static DynamicMethod CreateDynamicMethod(string name, Type? returnType, public override ObjectConstructor CreateParameterizedConstructor(MethodBase method) { - DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object[]) }, method.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString()!, typeof(object), new[] { typeof(object[]) }, method.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateMethodCallIL(method, generator, 0); @@ -61,7 +61,7 @@ public override ObjectConstructor CreateParameterizedConstructor(MethodB public override MethodCall CreateMethodCall(MethodBase method) { - DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString()!, typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateMethodCallIL(method, generator, 1); @@ -80,14 +80,14 @@ private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator generator.Emit(OpCodes.Ldlen); generator.Emit(OpCodes.Ldc_I4, args.Length); generator.Emit(OpCodes.Beq, argsOk); - generator.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(ReflectionUtils.EmptyTypes)); + generator.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(ReflectionUtils.EmptyTypes)!); generator.Emit(OpCodes.Throw); generator.MarkLabel(argsOk); if (!method.IsConstructor && !method.IsStatic) { - generator.PushInstance(method.DeclaringType); + generator.PushInstance(method.DeclaringType!); } LocalBuilder localConvertible = generator.DeclareLocal(typeof(IConvertible)); @@ -103,7 +103,7 @@ private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator if (parameterType.IsByRef) { - parameterType = parameterType.GetElementType(); + parameterType = parameterType.GetElementType()!; LocalBuilder localVariable = generator.DeclareLocal(parameterType); @@ -170,7 +170,7 @@ private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator if (parameterType.IsPrimitive()) { // for primitive types we need to handle type widening (e.g. short -> int) - MethodInfo toParameterTypeMethod = typeof(IConvertible) + MethodInfo? toParameterTypeMethod = typeof(IConvertible) .GetMethod("To" + parameterType.Name, new[] { typeof(IFormatProvider) }); if (toParameterTypeMethod != null) @@ -227,7 +227,7 @@ private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator } Type returnType = method.IsConstructor - ? method.DeclaringType + ? method.DeclaringType! : ((MethodInfo)method).ReturnType; if (returnType != typeof(void)) @@ -268,7 +268,7 @@ private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator } else { - ConstructorInfo constructorInfo = + ConstructorInfo? constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, ReflectionUtils.EmptyTypes, null); if (constructorInfo == null) @@ -284,7 +284,7 @@ private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator public override Func CreateGet(PropertyInfo propertyInfo) { - DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(object), new[] { typeof(T) }, propertyInfo.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(object), new[] { typeof(T) }, propertyInfo.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateGetPropertyIL(propertyInfo, generator); @@ -294,7 +294,7 @@ private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator private void GenerateCreateGetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) { - MethodInfo getMethod = propertyInfo.GetGetMethod(true); + MethodInfo? getMethod = propertyInfo.GetGetMethod(true); if (getMethod == null) { throw new ArgumentException("Property '{0}' does not have a getter.".FormatWith(CultureInfo.InvariantCulture, propertyInfo.Name)); @@ -302,7 +302,7 @@ private void GenerateCreateGetPropertyIL(PropertyInfo propertyInfo, ILGenerator if (!getMethod.IsStatic) { - generator.PushInstance(propertyInfo.DeclaringType); + generator.PushInstance(propertyInfo.DeclaringType!); } generator.CallMethod(getMethod); @@ -314,12 +314,12 @@ private void GenerateCreateGetPropertyIL(PropertyInfo propertyInfo, ILGenerator { if (fieldInfo.IsLiteral) { - object constantValue = fieldInfo.GetValue(null); + object constantValue = fieldInfo.GetValue(null)!; Func getter = o => constantValue; return getter; } - DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + fieldInfo.Name, typeof(T), new[] { typeof(object) }, fieldInfo.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + fieldInfo.Name, typeof(T), new[] { typeof(object) }, fieldInfo.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateGetFieldIL(fieldInfo, generator); @@ -331,7 +331,7 @@ private void GenerateCreateGetFieldIL(FieldInfo fieldInfo, ILGenerator generator { if (!fieldInfo.IsStatic) { - generator.PushInstance(fieldInfo.DeclaringType); + generator.PushInstance(fieldInfo.DeclaringType!); generator.Emit(OpCodes.Ldfld, fieldInfo); } else @@ -345,7 +345,7 @@ private void GenerateCreateGetFieldIL(FieldInfo fieldInfo, ILGenerator generator public override Action CreateSet(FieldInfo fieldInfo) { - DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateSetFieldIL(fieldInfo, generator); @@ -357,7 +357,7 @@ internal static void GenerateCreateSetFieldIL(FieldInfo fieldInfo, ILGenerator g { if (!fieldInfo.IsStatic) { - generator.PushInstance(fieldInfo.DeclaringType); + generator.PushInstance(fieldInfo.DeclaringType!); } generator.Emit(OpCodes.Ldarg_1); @@ -377,7 +377,7 @@ internal static void GenerateCreateSetFieldIL(FieldInfo fieldInfo, ILGenerator g public override Action CreateSet(PropertyInfo propertyInfo) { - DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType); + DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType!); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateSetPropertyIL(propertyInfo, generator); @@ -387,10 +387,10 @@ internal static void GenerateCreateSetFieldIL(FieldInfo fieldInfo, ILGenerator g internal static void GenerateCreateSetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) { - MethodInfo setMethod = propertyInfo.GetSetMethod(true); + MethodInfo setMethod = propertyInfo.GetSetMethod(true)!; if (!setMethod.IsStatic) { - generator.PushInstance(propertyInfo.DeclaringType); + generator.PushInstance(propertyInfo.DeclaringType!); } generator.Emit(OpCodes.Ldarg_1); diff --git a/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs b/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs index acb3e3a3b..51aa74133 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs @@ -64,7 +64,7 @@ private static void Init() { if (!_init) { - Type binderType = Type.GetType(BinderTypeName, false); + Type? binderType = Type.GetType(BinderTypeName, false); if (binderType == null) { throw new InvalidOperationException("Could not resolve type '{0}'. You may need to add a reference to Microsoft.CSharp.dll to work with dynamic types.".FormatWith(CultureInfo.InvariantCulture, BinderTypeName)); @@ -82,15 +82,15 @@ private static void Init() private static object CreateSharpArgumentInfoArray(params int[] values) { - Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName); - Type csharpArgumentInfoFlags = Type.GetType(CSharpArgumentInfoFlagsTypeName); + Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!; + Type csharpArgumentInfoFlags = Type.GetType(CSharpArgumentInfoFlagsTypeName, true)!; Array a = Array.CreateInstance(csharpArgumentInfoType, values.Length); for (int i = 0; i < values.Length; i++) { - MethodInfo createArgumentInfoMethod = csharpArgumentInfoType.GetMethod("Create", new[] { csharpArgumentInfoFlags, typeof(string) }); - object arg = createArgumentInfoMethod.Invoke(null, new object?[] { 0, null }); + MethodInfo createArgumentInfoMethod = csharpArgumentInfoType.GetMethod("Create", new[] { csharpArgumentInfoFlags, typeof(string) })!; + object arg = createArgumentInfoMethod.Invoke(null, new object?[] { 0, null })!; a.SetValue(arg, i); } @@ -99,16 +99,16 @@ private static object CreateSharpArgumentInfoArray(params int[] values) private static void CreateMemberCalls() { - Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true); - Type csharpBinderFlagsType = Type.GetType(CSharpBinderFlagsTypeName, true); - Type binderType = Type.GetType(BinderTypeName, true); + Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!; + Type csharpBinderFlagsType = Type.GetType(CSharpBinderFlagsTypeName, true)!; + Type binderType = Type.GetType(BinderTypeName, true)!; Type csharpArgumentInfoTypeEnumerableType = typeof(IEnumerable<>).MakeGenericType(csharpArgumentInfoType); - MethodInfo getMemberMethod = binderType.GetMethod("GetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }); + MethodInfo getMemberMethod = binderType.GetMethod("GetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType })!; _getMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getMemberMethod); - MethodInfo setMemberMethod = binderType.GetMethod("SetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }); + MethodInfo setMemberMethod = binderType.GetMethod("SetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType })!; _setMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(setMemberMethod); } #endif @@ -161,7 +161,7 @@ public NoThrowGetBinderMember(GetMemberBinder innerBinder) _innerBinder = innerBinder; } - public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) + public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject? errorSuggestion) { DynamicMetaObject retMetaObject = _innerBinder.Bind(target, CollectionUtils.ArrayEmpty()); @@ -183,7 +183,7 @@ public NoThrowSetBinderMember(SetMemberBinder innerBinder) _innerBinder = innerBinder; } - public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject errorSuggestion) + public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject? errorSuggestion) { DynamicMetaObject retMetaObject = _innerBinder.Bind(target, new DynamicMetaObject[] { value }); diff --git a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs index ea6d45302..a1b3bae9b 100644 --- a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs @@ -60,11 +60,11 @@ private static EnumInfo InitializeValuesAndNames(StructMultiKey() .Select(a => a.Value) .SingleOrDefault(); diff --git a/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs index 53a97ecab..36acc7c0c 100644 --- a/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs @@ -111,7 +111,7 @@ private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpres bool isByRef = false; if (parameterType.IsByRef) { - parameterType = parameterType.GetElementType(); + parameterType = parameterType.GetElementType()!; isByRef = true; } @@ -144,7 +144,7 @@ private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpres } else { - Expression readParameter = EnsureCastExpression(targetParameterExpression!, method.DeclaringType); + Expression readParameter = EnsureCastExpression(targetParameterExpression!, method.DeclaringType!); callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression); } @@ -194,7 +194,7 @@ public override Func CreateDefaultConstructor(Type type) // avoid error from expressions compiler because of abstract class if (type.IsAbstract()) { - return () => (T)Activator.CreateInstance(type); + return () => (T)Activator.CreateInstance(type)!; } try @@ -214,7 +214,7 @@ public override Func CreateDefaultConstructor(Type type) { // an error can be thrown if constructor is not valid on Win8 // will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag - return () => (T)Activator.CreateInstance(type); + return () => (T)Activator.CreateInstance(type)!; } } @@ -240,7 +240,7 @@ public override Func CreateDefaultConstructor(Type type) } else { - Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType); + Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType!); resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo); } @@ -266,7 +266,7 @@ public override Func CreateDefaultConstructor(Type type) } else { - Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType); + Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType!); fieldExpression = Expression.Field(sourceExpression, fieldInfo); } @@ -283,7 +283,7 @@ public override Func CreateDefaultConstructor(Type type) // use reflection for structs // expression doesn't correctly set value - if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly) + if (fieldInfo.DeclaringType!.IsValueType() || fieldInfo.IsInitOnly) { return LateBoundReflectionDelegateFactory.Instance.CreateSet(fieldInfo); } @@ -298,7 +298,7 @@ public override Func CreateDefaultConstructor(Type type) } else { - Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType); + Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType!); fieldExpression = Expression.Field(sourceExpression, fieldInfo); } @@ -319,7 +319,7 @@ public override Func CreateDefaultConstructor(Type type) // use reflection for structs // expression doesn't correctly set value - if (propertyInfo.DeclaringType.IsValueType()) + if (propertyInfo.DeclaringType!.IsValueType()) { return LateBoundReflectionDelegateFactory.Instance.CreateSet(propertyInfo); } @@ -345,7 +345,7 @@ public override Func CreateDefaultConstructor(Type type) } else { - Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType); + Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType!); setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter); } @@ -372,7 +372,7 @@ private Expression EnsureCastExpression(Expression expression, Type targetType, if (allowWidening && targetType.IsPrimitive()) { - MethodInfo toTargetTypeMethod = typeof(Convert) + MethodInfo? toTargetTypeMethod = typeof(Convert) .GetMethod("To" + targetType.Name, new[] { typeof(object) }); if (toTargetTypeMethod != null) diff --git a/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs b/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs index cb8166606..925219ff0 100644 --- a/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs @@ -60,7 +60,7 @@ private FSharpUtils(Assembly fsharpCoreAssembly) { FSharpCoreAssembly = fsharpCoreAssembly; - Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType"); + Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType")!; MethodInfo isUnionMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "IsUnion", BindingFlags.Public | BindingFlags.Static); IsUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(isUnionMethodInfo)!; @@ -68,23 +68,23 @@ private FSharpUtils(Assembly fsharpCoreAssembly) MethodInfo getUnionCasesMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "GetUnionCases", BindingFlags.Public | BindingFlags.Static); GetUnionCases = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getUnionCasesMethodInfo)!; - Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue"); + Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue")!; PreComputeUnionTagReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionTagReader"); PreComputeUnionReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionReader"); PreComputeUnionConstructor = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionConstructor"); - Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo"); + Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo")!; GetUnionCaseInfoName = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Name")!)!; GetUnionCaseInfoTag = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Tag")!)!; GetUnionCaseInfoDeclaringType = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("DeclaringType")!)!; - GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(unionCaseInfo.GetMethod("GetFields")); + GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(unionCaseInfo.GetMethod("GetFields")!); - Type listModule = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.ListModule"); - _ofSeq = listModule.GetMethod("OfSeq"); + Type listModule = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.ListModule")!; + _ofSeq = listModule.GetMethod("OfSeq")!; - _mapType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpMap`2"); + _mapType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpMap`2")!; } private static readonly object Lock = new object(); @@ -133,7 +133,7 @@ public static void EnsureInitialized(Assembly fsharpCoreAssembly) private static MethodInfo GetMethodWithNonPublicFallback(Type type, string methodName, BindingFlags bindingFlags) { - MethodInfo methodInfo = type.GetMethod(methodName, bindingFlags); + MethodInfo methodInfo = type.GetMethod(methodName, bindingFlags)!; // if no matching method then attempt to find with nonpublic flag // this is required because in WinApps some methods are private but always using NonPublic breaks medium trust @@ -141,7 +141,7 @@ private static MethodInfo GetMethodWithNonPublicFallback(Type type, string metho // https://github.com/JamesNK/Newtonsoft.Json/issues/821 if (methodInfo == null && (bindingFlags & BindingFlags.NonPublic) != BindingFlags.NonPublic) { - methodInfo = type.GetMethod(methodName, bindingFlags | BindingFlags.NonPublic); + methodInfo = type.GetMethod(methodName, bindingFlags | BindingFlags.NonPublic)!; } return methodInfo!; @@ -150,7 +150,7 @@ private static MethodInfo GetMethodWithNonPublicFallback(Type type, string metho private static MethodCall CreateFSharpFuncCall(Type type, string methodName) { MethodInfo innerMethodInfo = GetMethodWithNonPublicFallback(type, methodName, BindingFlags.Public | BindingFlags.Static); - MethodInfo invokeFunc = innerMethodInfo.ReturnType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance); + MethodInfo invokeFunc = innerMethodInfo.ReturnType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance)!; MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(innerMethodInfo); MethodCall invoke = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(invokeFunc)!; @@ -175,17 +175,17 @@ public ObjectConstructor CreateSeq(Type t) public ObjectConstructor CreateMap(Type keyType, Type valueType) { - MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator"); + MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator")!; MethodInfo creatorGeneric = creatorDefinition.MakeGenericMethod(keyType, valueType); - return (ObjectConstructor)creatorGeneric.Invoke(this, null); + return (ObjectConstructor)creatorGeneric.Invoke(this, null)!; } public ObjectConstructor BuildMapCreator() { Type genericMapType = _mapType.MakeGenericType(typeof(TKey), typeof(TValue)); - ConstructorInfo ctor = genericMapType.GetConstructor(new[] { typeof(IEnumerable>) }); + ConstructorInfo ctor = genericMapType.GetConstructor(new[] { typeof(IEnumerable>) })!; ObjectConstructor ctorDelegate = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(ctor); ObjectConstructor creator = args => diff --git a/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs b/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs index dfe5d45ea..8d7ba74d2 100644 --- a/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs @@ -116,17 +116,17 @@ internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type if (underlyingType.IsGenericType()) { Type underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition(); - string name = underlyingTypeDefinition.FullName; + string name = underlyingTypeDefinition.FullName!; - ImmutableCollectionTypeInfo definition = ArrayContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); + ImmutableCollectionTypeInfo? definition = ArrayContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); if (definition != null) { - Type createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); - Type builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); + Type? createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); + Type? builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); if (createdTypeDefinition != null && builderTypeDefinition != null) { - MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => m.Name == "CreateRange" && m.GetParameters().Length == 1); + MethodInfo? mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => m.Name == "CreateRange" && m.GetParameters().Length == 1); if (mb != null) { createdType = createdTypeDefinition.MakeGenericType(collectionItemType); @@ -148,17 +148,17 @@ internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, if (underlyingType.IsGenericType()) { Type underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition(); - string name = underlyingTypeDefinition.FullName; + string name = underlyingTypeDefinition.FullName!; - ImmutableCollectionTypeInfo definition = DictionaryContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); + ImmutableCollectionTypeInfo? definition = DictionaryContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); if (definition != null) { - Type createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); - Type builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); + Type? createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); + Type? builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); if (createdTypeDefinition != null && builderTypeDefinition != null) { - MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => + MethodInfo? mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => { ParameterInfo[] parameters = m.GetParameters(); diff --git a/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs b/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs index 9619e6996..74695ed5f 100644 --- a/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs @@ -289,6 +289,7 @@ public static void WriteEscapedJavaScriptString(TextWriter writer, string? s, ch } else { + MiscellaneousUtils.Assert(writeBuffer != null); writer.Write(writeBuffer, 0, UnicodeTextLength); } } @@ -386,7 +387,7 @@ private static Task WriteEscapedJavaScriptStringWithDelimitersAsync(TextWriter w bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { Task task = writer.WriteAsync(delimiter, cancellationToken); - if (!task.IsCompletedSucessfully()) + if (!task.IsCompletedSuccessfully()) { return WriteEscapedJavaScriptStringWithDelimitersAsync(task, writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } @@ -394,7 +395,7 @@ private static Task WriteEscapedJavaScriptStringWithDelimitersAsync(TextWriter w if (!StringUtils.IsNullOrEmpty(s)) { task = WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); - if (task.IsCompletedSucessfully()) + if (task.IsCompletedSuccessfully()) { return writer.WriteAsync(delimiter, cancellationToken); } diff --git a/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs index 277f1ebb6..67526268e 100644 --- a/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs @@ -50,7 +50,7 @@ public override ObjectConstructor CreateParameterizedConstructor(MethodB return a => c.Invoke(a); } - return a => method.Invoke(null, a); + return a => method.Invoke(null, a)!; } public override MethodCall CreateMethodCall(MethodBase method) @@ -71,10 +71,14 @@ public override Func CreateDefaultConstructor(Type type) if (type.IsValueType()) { - return () => (T)Activator.CreateInstance(type); + return () => (T)Activator.CreateInstance(type)!; } - ConstructorInfo constructorInfo = ReflectionUtils.GetDefaultConstructor(type, true); + ConstructorInfo? constructorInfo = ReflectionUtils.GetDefaultConstructor(type, true); + if (constructorInfo == null) + { + throw new InvalidOperationException("Unable to find default constructor for " + type.FullName); + } return () => (T)constructorInfo.Invoke(null); } diff --git a/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs b/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs index 137ec4454..c469ce647 100644 --- a/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs @@ -92,7 +92,7 @@ public static string ToString(object? value) return "{null}"; } - return (value is string s) ? @"""" + s + @"""" : value!.ToString(); + return (value is string s) ? @"""" + s + @"""" : value!.ToString()!; } public static int ByteArrayCompare(byte[] a1, byte[] a2) @@ -131,7 +131,7 @@ public static string GetLocalName(string qualifiedName) public static void GetQualifiedNameParts(string qualifiedName, out string? prefix, out string localName) { - int colonPosition = qualifiedName.IndexOf(':'); + int colonPosition = StringUtils.IndexOf(qualifiedName, ':'); if ((colonPosition == -1 || colonPosition == 0) || (qualifiedName.Length - 1) == colonPosition) { diff --git a/Src/Newtonsoft.Json/Utilities/NullableAttributes.cs b/Src/Newtonsoft.Json/Utilities/NullableAttributes.cs index fa1f55e97..5733cb801 100644 --- a/Src/Newtonsoft.Json/Utilities/NullableAttributes.cs +++ b/Src/Newtonsoft.Json/Utilities/NullableAttributes.cs @@ -23,6 +23,8 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion +#if !HAVE_NULLABLE_ATTRIBUTES + namespace System.Diagnostics.CodeAnalysis { /// Specifies that an output will not be null even if the corresponding type allows it. @@ -71,4 +73,6 @@ internal class DoesNotReturnIfAttribute : Attribute /// Gets the condition parameter value. public bool ParameterValue { get; } } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs index fd3cbaea3..f3d594244 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -177,7 +177,7 @@ private static string GetFullyQualifiedTypeName(Type t, ISerializationBinder? bi return typeName + (assemblyName == null ? "" : ", " + assemblyName); } - return t.AssemblyQualifiedName; + return t.AssemblyQualifiedName!; } private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) @@ -245,12 +245,12 @@ public static bool HasDefaultConstructor(Type t, bool nonPublic) return (GetDefaultConstructor(t, nonPublic) != null); } - public static ConstructorInfo GetDefaultConstructor(Type t) + public static ConstructorInfo? GetDefaultConstructor(Type t) { return GetDefaultConstructor(t, false); } - public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic) + public static ConstructorInfo? GetDefaultConstructor(Type t, bool nonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (nonPublic) @@ -283,14 +283,14 @@ public static bool IsNullableType(Type t) public static Type EnsureNotNullableType(Type t) { return (IsNullableType(t)) - ? Nullable.GetUnderlyingType(t) + ? Nullable.GetUnderlyingType(t)! : t; } public static Type EnsureNotByRefType(Type t) { return (t.IsByRef && t.HasElementType) - ? t.GetElementType() + ? t.GetElementType()! : t; } @@ -370,8 +370,9 @@ public static bool InheritsGenericDefinition(Type type, Type genericClassDefinit return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } - private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type? implementingType) + private static bool InheritsGenericDefinitionInternal(Type type, Type genericClassDefinition, out Type? implementingType) { + Type? currentType = type; do { if (currentType.IsGenericType() && genericClassDefinition == currentType.GetGenericTypeDefinition()) @@ -461,7 +462,7 @@ public static Type GetMemberUnderlyingType(MemberInfo member) case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; case MemberTypes.Event: - return ((EventInfo)member).EventHandlerType; + return ((EventInfo)member).EventHandlerType!; case MemberTypes.Method: return ((MethodInfo)member).ReturnType; default: @@ -509,7 +510,7 @@ public static bool IsIndexedProperty(PropertyInfo property) /// The member. /// The target object. /// The member's value on the object. - public static object GetMemberValue(MemberInfo member, object target) + public static object? GetMemberValue(MemberInfo member, object target) { ValidationUtils.ArgumentNotNull(member, nameof(member)); ValidationUtils.ArgumentNotNull(target, nameof(target)); @@ -713,7 +714,7 @@ private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags return false; } - Type declaringType = propertyInfo.DeclaringType; + Type declaringType = propertyInfo.DeclaringType!; if (!declaringType.IsGenericType()) { return false; @@ -884,7 +885,7 @@ public static Attribute[] GetAttributes(object provider, Type? attributeType, bo return null; } - public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) + public static MemberInfo? GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) { const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; @@ -916,8 +917,10 @@ public static IEnumerable GetFields(Type targetType, BindingFlags bin } #if !PORTABLE - private static void GetChildPrivateFields(IList initialFields, Type targetType, BindingFlags bindingAttr) + private static void GetChildPrivateFields(IList initialFields, Type type, BindingFlags bindingAttr) { + Type? targetType = type; + // fix weirdness with private FieldInfos only being returned for the current Type // find base type fields and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) @@ -960,7 +963,7 @@ public static IEnumerable GetProperties(Type targetType, BindingFl PropertyInfo member = propertyInfos[i]; if (member.DeclaringType != targetType) { - PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member); + PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType!, member)!; propertyInfos[i] = declaredMember; } } @@ -975,13 +978,14 @@ public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlag : bindingAttr; } - private static void GetChildPrivateProperties(IList initialProperties, Type targetType, BindingFlags bindingAttr) + private static void GetChildPrivateProperties(IList initialProperties, Type type, BindingFlags bindingAttr) { // fix weirdness with private PropertyInfos only being returned for the current Type // find base type properties and add them to result // also find base properties that have been hidden by subtype properties with the same name + Type? targetType = type; while ((targetType = targetType.BaseType()) != null) { foreach (PropertyInfo propertyInfo in targetType.GetProperties(bindingAttr)) @@ -1025,11 +1029,11 @@ private static void GetChildPrivateProperties(IList initialPropert } else { - Type subTypePropertyDeclaringType = subTypeProperty.GetBaseDefinition()?.DeclaringType ?? subTypeProperty.DeclaringType; + Type subTypePropertyDeclaringType = subTypeProperty.GetBaseDefinition()?.DeclaringType ?? subTypeProperty.DeclaringType!; int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name && p.IsVirtual() - && (p.GetBaseDefinition()?.DeclaringType ?? p.DeclaringType).IsAssignableFrom(subTypePropertyDeclaringType)); + && (p.GetBaseDefinition()?.DeclaringType ?? p.DeclaringType!).IsAssignableFrom(subTypePropertyDeclaringType)); // don't add a virtual property that has an override if (index == -1) diff --git a/Src/Newtonsoft.Json/Utilities/StringBuffer.cs b/Src/Newtonsoft.Json/Utilities/StringBuffer.cs index 13f4f8666..bc62f825c 100644 --- a/Src/Newtonsoft.Json/Utilities/StringBuffer.cs +++ b/Src/Newtonsoft.Json/Utilities/StringBuffer.cs @@ -107,7 +107,7 @@ public override string ToString() public string ToString(int start, int length) { - // TODO: validation + MiscellaneousUtils.Assert(_buffer != null); return new string(_buffer, start, length); } diff --git a/Src/Newtonsoft.Json/Utilities/StringUtils.cs b/Src/Newtonsoft.Json/Utilities/StringUtils.cs index e176c88fd..ad7637895 100644 --- a/Src/Newtonsoft.Json/Utilities/StringUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/StringUtils.cs @@ -128,7 +128,7 @@ public static void ToCharAsUnicode(char c, char[] buffer) buffer[5] = MathUtils.IntToHex(c & '\x000f'); } - public static TSource ForgivingCaseSensitiveFind(this IEnumerable source, Func valueSelector, string testValue) + public static TSource? ForgivingCaseSensitiveFind(this IEnumerable source, Func valueSelector, string testValue) { if (source == null) { @@ -303,6 +303,24 @@ public static bool IsLowSurrogate(char c) #endif } + public static int IndexOf(string s, char c) + { +#if HAVE_INDEXOF_STRING_COMPARISON + return s.IndexOf(c, StringComparison.Ordinal); +#else + return s.IndexOf(c); +#endif + } + + public static string Replace(string s, string oldValue, string newValue) + { +#if HAVE_REPLACE_STRING_COMPARISON + return s.Replace(oldValue, newValue, StringComparison.Ordinal); +#else + return s.Replace(oldValue, newValue); +#endif + } + public static bool StartsWith(this string source, char value) { return (source.Length > 0 && source[0] == value); diff --git a/Src/Newtonsoft.Json/Utilities/StructMultiKey.cs b/Src/Newtonsoft.Json/Utilities/StructMultiKey.cs index 10428aaaf..a36d1d152 100644 --- a/Src/Newtonsoft.Json/Utilities/StructMultiKey.cs +++ b/Src/Newtonsoft.Json/Utilities/StructMultiKey.cs @@ -43,7 +43,7 @@ public override int GetHashCode() return (Value1?.GetHashCode() ?? 0) ^ (Value2?.GetHashCode() ?? 0); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is StructMultiKey key)) { diff --git a/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs b/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs index 2e135f0ac..0413f22b0 100644 --- a/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs +++ b/Src/Newtonsoft.Json/Utilities/ThreadSafeStore.cs @@ -36,7 +36,7 @@ namespace Newtonsoft.Json.Utilities { - internal class ThreadSafeStore + internal class ThreadSafeStore where TKey : notnull { #if HAVE_CONCURRENT_DICTIONARY private readonly ConcurrentDictionary _concurrentStore; diff --git a/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs b/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs index 77b756915..934302d65 100644 --- a/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs +++ b/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs @@ -171,7 +171,7 @@ public static bool IsGenericTypeDefinition(this Type type) #endif } - public static Type BaseType(this Type type) + public static Type? BaseType(this Type type) { #if HAVE_FULL_REFLECTION return type.BaseType; @@ -580,7 +580,7 @@ public static bool IsPrimitive(this Type type) public static bool AssignableToTypeName(this Type type, string fullTypeName, bool searchInterfaces, [NotNullWhen(true)]out Type? match) { - Type current = type; + Type? current = type; while (current != null) { @@ -616,7 +616,7 @@ public static bool AssignableToTypeName(this Type type, string fullTypeName, boo public static bool ImplementInterface(this Type type, Type interfaceType) { - for (Type currentType = type; currentType != null; currentType = currentType.BaseType()) + for (Type? currentType = type; currentType != null; currentType = currentType.BaseType()) { IEnumerable interfaces = currentType.GetInterfaces(); foreach (Type i in interfaces) From 5803c7722af4cf0dc3984e55404694aab09e51bf Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Mon, 16 May 2022 17:13:53 +0800 Subject: [PATCH 17/30] Update .NET 6 tests (#2678) --- .../Benchmarks/LowLevelBenchmarks.cs | 2 +- .../Bson/BsonReaderTests.cs | 4 +- .../Bson/BsonWriterAsyncTests.cs | 4 +- .../Bson/BsonWriterTests.cs | 4 +- .../Converters/BinaryConverterTests.cs | 4 +- .../Converters/DataSetConverterTests.cs | 2 +- .../Converters/DataTableConverterTests.cs | 2 +- .../DiscriminatedUnionConverterTests.cs | 2 +- .../Converters/IsoDateTimeConverterTests.cs | 2 +- .../Converters/XmlNodeConverterTest.cs | 34 ++++---- Src/Newtonsoft.Json.Tests/DemoTests.cs | 12 +-- .../ConditionalPropertiesTests.cs | 2 +- .../ConvertingJsonAndXmlTests.cs | 2 +- .../Documentation/JsonSchemaTests.cs | 2 +- .../Documentation/LinqToJsonTests.cs | 2 +- .../Documentation/PerformanceTests.cs | 2 +- .../ReadingAndWritingJsonTests.cs | 2 +- .../Samples/Json/CustomJsonReader.cs | 2 +- .../Samples/Json/CustomJsonWriter.cs | 2 +- .../Samples/Linq/DeserializeWithLinq.cs | 2 +- .../Samples/Linq/SerializeWithLinq.cs | 2 +- .../Samples/Serializer/CustomTraceWriter.cs | 2 +- .../Samples/Serializer/DeserializeDataSet.cs | 2 +- .../Serializer/DeserializeDateFormatString.cs | 2 +- .../DeserializeWithDependencyInjection.cs | 2 +- .../Samples/Serializer/SerializeDataSet.cs | 2 +- .../Samples/Xml/ConvertXmlToJson.cs | 2 +- .../Samples/Xml/ConvertXmlToJsonForceArray.cs | 2 +- .../Documentation/SerializationTests.cs | 2 +- .../Documentation/TraceWriterTests.cs | 2 +- Src/Newtonsoft.Json.Tests/ExceptionTests.cs | 4 +- Src/Newtonsoft.Json.Tests/Issues/Issue1327.cs | 6 +- Src/Newtonsoft.Json.Tests/Issues/Issue1404.cs | 2 +- Src/Newtonsoft.Json.Tests/Issues/Issue1445.cs | 2 +- Src/Newtonsoft.Json.Tests/Issues/Issue1569.cs | 2 +- Src/Newtonsoft.Json.Tests/Issues/Issue1597.cs | 2 +- Src/Newtonsoft.Json.Tests/Issues/Issue1620.cs | 2 +- Src/Newtonsoft.Json.Tests/Issues/Issue1734.cs | 2 +- Src/Newtonsoft.Json.Tests/Issues/Issue1757.cs | 2 +- Src/Newtonsoft.Json.Tests/Issues/Issue1798.cs | 2 +- Src/Newtonsoft.Json.Tests/JsonConvertTest.cs | 4 +- .../ExceptionHandlingAsyncTests.cs | 4 +- .../ExceptionHandlingTests.cs | 6 +- .../JsonTextReaderTests/FloatTests.cs | 2 +- .../JsonTextReaderTests/MiscTests.cs | 2 +- .../JsonTextReaderTests/ParseAsyncTests.cs | 4 +- .../JsonTextReaderTests/ParseTests.cs | 6 +- .../JsonTextReaderTests/ReadAsyncTests.cs | 8 +- .../JsonTextReaderTests/ReadTests.cs | 8 +- .../JsonTextWriterAsyncTests.cs | 6 +- .../JsonTextWriterTest.cs | 6 +- .../JsonValidatingReaderTests.cs | 6 +- .../JPropertyDescriptorTests.cs | 2 +- .../Linq/DynamicTests.cs | 26 +++--- Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs | 2 +- .../Linq/JObjectTests.cs | 14 ++-- .../Linq/JPropertyTests.cs | 2 +- .../Linq/JTokenReaderAsyncTests.cs | 6 +- .../Linq/JTokenReaderTest.cs | 6 +- Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs | 12 +-- .../Linq/JTokenWriterAsyncTests.cs | 8 +- .../Linq/JTokenWriterTest.cs | 8 +- Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs | 20 ++--- .../Linq/JsonPath/JPathExecuteTests.cs | 4 +- .../Linq/LinqToJsonTest.cs | 2 +- .../Newtonsoft.Json.Tests.csproj | 2 +- .../Schema/JsonSchemaGeneratorTests.cs | 10 +-- ...lCasePropertyNamesContractResolverTests.cs | 2 +- .../Serialization/ContractResolverTests.cs | 4 +- .../Serialization/DependencyInjectionTests.cs | 2 +- .../Serialization/DynamicTests.cs | 2 +- .../Serialization/FSharpTests.cs | 2 +- .../JsonSerializerCollectionsTests.cs | 18 ++--- .../Serialization/JsonSerializerTest.cs | 80 +++++++++---------- .../MetadataPropertyHandlingTests.cs | 2 +- .../ReferenceLoopHandlingTests.cs | 2 +- .../ReflectionAttributeProviderTests.cs | 4 +- .../SerializationEventAttributeTests.cs | 4 +- .../Serialization/TraceWriterTests.cs | 10 +-- .../Serialization/TypeNameHandlingTests.cs | 10 +-- .../Serialization/WebApiIntegrationTests.cs | 6 +- .../TestObjects/AnswerFilterModel.cs | 2 +- .../TestObjects/AttachmentReadConverter.cs | 2 +- .../TestObjects/ConsoleWriter.cs | 2 +- .../TestObjects/ConverableMembers.cs | 2 +- .../TestObjects/ConvertableIntTestClass.cs | 2 +- .../TestObjects/ConvertibleInt.cs | 2 +- .../TestObjects/CustomerDataSet.cs | 2 +- .../TestObjects/EncodingReadConverter.cs | 2 +- .../TestObjects/GeometricForms/Shape.cs | 2 +- .../TestObjects/GeometricForms/Tags.cs | 2 +- .../TestObjects/IMyInterface.cs | 2 +- .../TestObjects/ListOfIds.cs | 2 +- .../TestObjects/MailAddressReadConverter.cs | 2 +- .../TestObjects/Money/Currency.cs | 2 +- .../TestObjects/Money/Tags.cs | 2 +- .../TestObjects/MyInterfaceConverter.cs | 2 +- .../NullableStructPropertyClass.cs | 2 +- .../TestObjects/PersonSerializable.cs | 2 +- .../PreserveReferencesCallbackTestObject.cs | 2 +- .../TestObjects/Ratio.cs | 2 +- .../SerializableContractResolver.cs | 2 +- .../TestObjects/StringDictionaryTestClass.cs | 2 +- .../TestObjects/StructISerializable.cs | 2 +- .../TestObjects/TraceWriter.cs | 2 +- .../TestObjects/TypeConverterJsonConverter.cs | 2 +- .../TestObjects/TypedSubHashtable.cs | 2 +- .../Serialization/DefaultContractResolver.cs | 2 +- 108 files changed, 262 insertions(+), 262 deletions(-) diff --git a/Src/Newtonsoft.Json.Tests/Benchmarks/LowLevelBenchmarks.cs b/Src/Newtonsoft.Json.Tests/Benchmarks/LowLevelBenchmarks.cs index 3aae21b04..9c5487456 100644 --- a/Src/Newtonsoft.Json.Tests/Benchmarks/LowLevelBenchmarks.cs +++ b/Src/Newtonsoft.Json.Tests/Benchmarks/LowLevelBenchmarks.cs @@ -35,7 +35,7 @@ using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Newtonsoft.Json.Utilities; -#if !PORTABLE || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD2_0 || NET6_0_OR_GREATER using MemberTypes = System.Reflection.MemberTypes; using BindingFlags = System.Reflection.BindingFlags; #else diff --git a/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs b/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs index 9c8c7f955..1998ff982 100644 --- a/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs +++ b/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs @@ -31,7 +31,7 @@ using System.Runtime.Serialization; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -1495,7 +1495,7 @@ public void Utf8Text() Assert.AreEqual(badText, (string)o["test"]); } -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER public class BigIntegerTestClass { public BigInteger Blah { get; set; } diff --git a/Src/Newtonsoft.Json.Tests/Bson/BsonWriterAsyncTests.cs b/Src/Newtonsoft.Json.Tests/Bson/BsonWriterAsyncTests.cs index ff465efd6..e86bc6f46 100644 --- a/Src/Newtonsoft.Json.Tests/Bson/BsonWriterAsyncTests.cs +++ b/Src/Newtonsoft.Json.Tests/Bson/BsonWriterAsyncTests.cs @@ -26,7 +26,7 @@ #pragma warning disable 618 #if !(NET20 || NET35 || NET40 || PORTABLE40) using System; -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -499,7 +499,7 @@ public async Task DateTimeZoneHandlingAsync() Assert.AreEqual("10-00-00-00-09-30-00-C8-88-07-6B-DC-00-00-00-00", (BitConverter.ToString(ms.ToArray()))); } -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task WriteBigIntegerAsync() { diff --git a/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs b/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs index ae8b61692..850c60a5f 100644 --- a/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Bson/BsonWriterTests.cs @@ -26,7 +26,7 @@ #pragma warning disable 618 using System; using System.Collections.Generic; -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -798,7 +798,7 @@ public void WriteStringReadGuid() Assert.AreEqual(c.AGuid, c2.AGuid.ToString()); } -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void WriteBigInteger() { diff --git a/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs index 80f96d6fe..fa420c823 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/BinaryConverterTests.cs @@ -28,7 +28,7 @@ #if !(NET20 || DNXCORE50) using System.Data.Linq; #endif -#if !DNXCORE50 || NETSTANDARD2_0 +#if !DNXCORE50 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Data.SqlTypes; #endif using System.Text; @@ -121,7 +121,7 @@ public void SerializeByteArrayClass() }", json); } -#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class SqlBinaryClass { public SqlBinary SqlBinary { get; set; } diff --git a/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs index 3c1274228..ff3534b16 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/DataSetConverterTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using Newtonsoft.Json.Converters; #if DNXCORE50 diff --git a/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs index 610760768..77977febf 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/DataTableConverterTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.IO; using System.Text; using Newtonsoft.Json.Bson; diff --git a/Src/Newtonsoft.Json.Tests/Converters/DiscriminatedUnionConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/DiscriminatedUnionConverterTests.cs index 7cac6eba2..3431bb53a 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/DiscriminatedUnionConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/DiscriminatedUnionConverterTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET40 || NET35 || NET20 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET40 || NET35 || NET20 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Diagnostics; using System.Reflection; using Microsoft.FSharp.Core; diff --git a/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs index 5f0052302..0ee769cf1 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs @@ -123,7 +123,7 @@ public void SerializeCustomFormattedDateTime() Assert.AreEqual(2006, d.Year); } -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeFormattedDateTimeNewZealandCulture() { diff --git a/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs b/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs index fb7b28be8..e621feb37 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; @@ -58,7 +58,7 @@ namespace Newtonsoft.Json.Tests.Converters [TestFixture] public class XmlNodeConverterTest : TestFixtureBase { -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER private string SerializeXmlNode(XmlNode node) { string json = JsonConvert.SerializeXmlNode(node, Formatting.Indented); @@ -151,7 +151,7 @@ private string IndentXml(string xml) return sw.ToString(); } -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeXmlNode_DefaultDate() { @@ -569,7 +569,7 @@ public void MultipleNamespacesXDocument() } #endif -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void MultipleNamespacesXmlDocument() { @@ -748,7 +748,7 @@ public void GroupElementsOfTheSameName() ", doc.ToString()); } -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeEmptyDocument() { @@ -794,7 +794,7 @@ public void SerializeAndDeserializeXmlWithNamespaceInChildrenAndNoValueInChildre Assert.IsTrue(equals); } -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeUndeclaredNamespacePrefix() { @@ -809,7 +809,7 @@ public void DeserializeUndeclaredNamespacePrefix() #endif #endif -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeMultipleRootElements() { @@ -1604,7 +1604,7 @@ public void NestedArrays() ] }"; -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER XmlDocument newDoc = JsonConvert.DeserializeXmlNode(json, "myRoot"); string xml = IndentXml(newDoc.InnerXml); @@ -1642,7 +1642,7 @@ public void NestedArrays() ", IndentXml(newXDoc.ToString(SaveOptions.DisableFormatting))); #endif -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER string newJson = JsonConvert.SerializeXmlNode(newDoc, Formatting.Indented); Console.WriteLine(newJson); #endif @@ -1667,7 +1667,7 @@ public void RoundTripNestedArrays() ] }"; -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER XmlDocument newDoc = JsonConvert.DeserializeXmlNode(json, "myRoot", true); StringAssert.AreEqual(@" @@ -1703,7 +1703,7 @@ public void RoundTripNestedArrays() ", IndentXml(newXDoc.ToString(SaveOptions.DisableFormatting))); #endif -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER string newJson = JsonConvert.SerializeXmlNode(newDoc, Formatting.Indented, true); StringAssert.AreEqual(json, newJson); #endif @@ -1729,7 +1729,7 @@ public void MultipleNestedArraysToXml() ] }"; -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER XmlDocument newDoc = JsonConvert.DeserializeXmlNode(json, "myRoot"); Assert.AreEqual(@"113150assets/images/resized/0001/1070/11070v1-max-150x150.jpg189250assets/images/resized/0001/1070/11070v1-max-250x250.jpg341450assets/images/resized/0001/1070/11070v1-max-450x450.jpg", newDoc.InnerXml); @@ -1742,7 +1742,7 @@ public void MultipleNestedArraysToXml() #endif } -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void Encoding() { @@ -1757,7 +1757,7 @@ public void Encoding() } #endif -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeComment() { @@ -2808,7 +2808,7 @@ public void DeserializeXNodeDefaultNamespace() } #endif -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeXmlNodeDefaultNamespace() { @@ -3136,7 +3136,7 @@ public void SerializeAndDeserializeXElementWithNamespaceInChildrenRootDontHaveNa } #endif -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeAndDeserializeXmlElementWithNamespaceInChildrenRootDontHaveNameSpace() { @@ -3155,7 +3155,7 @@ public void SerializeAndDeserializeXmlElementWithNamespaceInChildrenRootDontHave Assert.AreEqual(@"AsdAAAadad", xmlBack.OuterXml); } -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeBigInteger() { diff --git a/Src/Newtonsoft.Json.Tests/DemoTests.cs b/Src/Newtonsoft.Json.Tests/DemoTests.cs index 51b781243..5c24ed448 100644 --- a/Src/Newtonsoft.Json.Tests/DemoTests.cs +++ b/Src/Newtonsoft.Json.Tests/DemoTests.cs @@ -24,11 +24,11 @@ #endregion using System; -#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Buffers; #endif using System.Collections.Generic; -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Data; #endif using System.IO; @@ -596,7 +596,7 @@ public void MergeJson() }", json); } -#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ArrayPooling() { @@ -614,7 +614,7 @@ public void ArrayPooling() } #endif -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeDataTable() { @@ -681,7 +681,7 @@ public void JsonPathRegex() Assert.AreEqual(1, newtonsoftPackages.Count); } -#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task AsyncDemo() { @@ -705,7 +705,7 @@ public async Task AsyncDemo() #endif } -#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class JsonArrayPool : IArrayPool { public static readonly JsonArrayPool Instance = new JsonArrayPool(); diff --git a/Src/Newtonsoft.Json.Tests/Documentation/ConditionalPropertiesTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/ConditionalPropertiesTests.cs index a5eae45ea..ce45016da 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/ConditionalPropertiesTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/ConditionalPropertiesTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET35 || NET20 || PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/ConvertingJsonAndXmlTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/ConvertingJsonAndXmlTests.cs index b3e0486ca..633211862 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/ConvertingJsonAndXmlTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/ConvertingJsonAndXmlTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET35 || NET20 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/JsonSchemaTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/JsonSchemaTests.cs index bccc3cfde..29fb5f4ca 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/JsonSchemaTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/JsonSchemaTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET40 || NET35 || NET20 || PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET40 || NET35 || NET20 || PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER #pragma warning disable 618 using System; using System.Collections.Generic; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs index 60efb478e..af55e482d 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/LinqToJsonTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/PerformanceTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/PerformanceTests.cs index 93f549bf9..f290a5b4b 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/PerformanceTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/PerformanceTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET40 || NET35 || NET20 || PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET40 || NET35 || NET20 || PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/ReadingAndWritingJsonTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/ReadingAndWritingJsonTests.cs index f01b19380..f154abf1a 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/ReadingAndWritingJsonTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/ReadingAndWritingJsonTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET40 || NET35 || NET20 || PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET40 || NET35 || NET20 || PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonReader.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonReader.cs index 3c5dc7168..2cf77075f 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonReader.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonReader.cs @@ -39,7 +39,7 @@ #endif -#if !(DNXCORE50 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(DNXCORE50 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER namespace Newtonsoft.Json.Tests.Documentation.Samples.Json { diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonWriter.cs index 010bd3b7a..51860f956 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonWriter.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Json/CustomJsonWriter.cs @@ -39,7 +39,7 @@ #endif -#if !(DNXCORE50 || NET20) || NETSTANDARD2_0 +#if !(DNXCORE50 || NET20) || NETSTANDARD2_0 || NET6_0_OR_GREATER namespace Newtonsoft.Json.Tests.Documentation.Samples.Json { diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeserializeWithLinq.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeserializeWithLinq.cs index 4a1bd9d39..0192f6d07 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeserializeWithLinq.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/DeserializeWithLinq.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !DNXCORE50 || NETSTANDARD2_0 +#if !DNXCORE50 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/SerializeWithLinq.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/SerializeWithLinq.cs index 89701f8a9..18c59428a 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/SerializeWithLinq.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Linq/SerializeWithLinq.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !DNXCORE50 || NETSTANDARD2_0 +#if !DNXCORE50 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomTraceWriter.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomTraceWriter.cs index c764505bd..b3306dde8 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomTraceWriter.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomTraceWriter.cs @@ -37,7 +37,7 @@ #endif -#if !(DNXCORE50 || NET20 || NET35) || NETSTANDARD2_0 +#if !(DNXCORE50 || NET20 || NET35) || NETSTANDARD2_0 || NET6_0_OR_GREATER namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer { diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDataSet.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDataSet.cs index 78e65c637..ec7605bea 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDataSet.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDataSet.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(DNXCORE50 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 +#if !(DNXCORE50 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDateFormatString.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDateFormatString.cs index dc7a0f0d1..1818ae686 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDateFormatString.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeDateFormatString.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !DNXCORE50 || NETSTANDARD2_0 +#if !DNXCORE50 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeWithDependencyInjection.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeWithDependencyInjection.cs index faceabe97..c15e3eb08 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeWithDependencyInjection.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/DeserializeWithDependencyInjection.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET20 || NET35 || NET40 || DNXCORE50 || PORTABLE40 || PORTABLE) || NETSTANDARD1_0 || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || NET40 || DNXCORE50 || PORTABLE40 || PORTABLE) || NETSTANDARD1_0 || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDataSet.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDataSet.cs index 45f7dcb86..a4ccdebc2 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDataSet.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/SerializeDataSet.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(DNXCORE50 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 +#if !(DNXCORE50 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJson.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJson.cs index 25c4c4293..856f8cbcb 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJson.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJson.cs @@ -36,7 +36,7 @@ #endif -#if !(DNXCORE50 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 +#if !(DNXCORE50 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER namespace Newtonsoft.Json.Tests.Documentation.Samples.Xml { diff --git a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJsonForceArray.cs b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJsonForceArray.cs index aeaf7fef3..35b0a3eda 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJsonForceArray.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/Samples/Xml/ConvertXmlToJsonForceArray.cs @@ -36,7 +36,7 @@ #endif -#if !(NET20 || DNXCORE50 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 +#if !(NET20 || DNXCORE50 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER namespace Newtonsoft.Json.Tests.Documentation.Samples.Xml { diff --git a/Src/Newtonsoft.Json.Tests/Documentation/SerializationTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/SerializationTests.cs index fbfbd3a8e..5bb3c6d5a 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/SerializationTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/SerializationTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET35 || NET20 || PORTABLE || DNXCORE50) || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Src/Newtonsoft.Json.Tests/Documentation/TraceWriterTests.cs b/Src/Newtonsoft.Json.Tests/Documentation/TraceWriterTests.cs index b40faea68..c7837e315 100644 --- a/Src/Newtonsoft.Json.Tests/Documentation/TraceWriterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Documentation/TraceWriterTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; using System.ComponentModel; diff --git a/Src/Newtonsoft.Json.Tests/ExceptionTests.cs b/Src/Newtonsoft.Json.Tests/ExceptionTests.cs index ff0b1148c..85714d7af 100644 --- a/Src/Newtonsoft.Json.Tests/ExceptionTests.cs +++ b/Src/Newtonsoft.Json.Tests/ExceptionTests.cs @@ -25,7 +25,7 @@ using System; using System.IO; -#if !(PORTABLE || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Runtime.Serialization.Formatters.Binary; #endif using Newtonsoft.Json.Schema; @@ -105,7 +105,7 @@ public void JsonSchemaException() } #pragma warning restore 618 -#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void BinarySerializeException() { diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue1327.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue1327.cs index 0d2f665a6..674364110 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue1327.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue1327.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; using System.Linq; @@ -47,7 +47,7 @@ namespace Newtonsoft.Json.Tests.Issues [TestFixture] public class Issue1327 : TestFixtureBase { -#if !PORTABLE || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD2_0 || NET6_0_OR_GREATER public class PersonWithXmlNode { public XmlNode TestXml { get; set; } @@ -71,7 +71,7 @@ public class PersonWithXObject } #endif -#if !PORTABLE || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void Test_XmlNode() { diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue1404.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue1404.cs index 51025c164..a0ec4ad9a 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue1404.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue1404.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if NETSTANDARD2_0 +#if NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Data; using System.IO; diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue1445.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue1445.cs index a641f44ea..72d4fa189 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue1445.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue1445.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(PORTABLE) || NETSTANDARD2_0 +#if !(PORTABLE) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Data; using System.Linq; diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue1569.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue1569.cs index d2552b831..f346fade7 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue1569.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue1569.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.IO; using System.Text; diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue1597.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue1597.cs index 4d2bdda53..91a8d4373 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue1597.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue1597.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET20 || NET35 || NET40 || PORTABLE40 || PORTABLE) || NETSTANDARD1_0 || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || NET40 || PORTABLE40 || PORTABLE) || NETSTANDARD1_0 || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections; using System.Collections.Generic; diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue1620.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue1620.cs index 0101e813e..6f673f963 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue1620.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue1620.cs @@ -36,7 +36,7 @@ using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; -#if PORTABLE && !NETSTANDARD2_0 +#if PORTABLE && !(NETSTANDARD2_0 || NET6_0_OR_GREATER) using BindingFlags = Newtonsoft.Json.Utilities.BindingFlags; #else using BindingFlags = System.Reflection.BindingFlags; diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue1734.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue1734.cs index a84475196..ec8724dc1 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue1734.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue1734.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq.JsonPath; using System; diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue1757.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue1757.cs index 83704f5ab..d1af5c88e 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue1757.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue1757.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if (NETSTANDARD2_0) +#if (NETSTANDARD2_0 || NET6_0_OR_GREATER) using System; using System.Collections; using System.Collections.Generic; diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue1798.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue1798.cs index b3ffc3c6f..1a8c7dc0e 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue1798.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue1798.cs @@ -90,7 +90,7 @@ public void Test_DefaultContractResolver() var objectContract = (JsonObjectContract) resolver.ResolveContract(typeof(NonSerializableException)); Assert.IsFalse(objectContract.Properties.Contains("TargetSite")); -#if (PORTABLE40 || PORTABLE) && !(NETSTANDARD2_0 || NETSTANDARD1_3) +#if (PORTABLE40 || PORTABLE) && !(NETSTANDARD2_0 || NETSTANDARD1_3 || NET6_0_OR_GREATER) objectContract = (JsonObjectContract) resolver.ResolveContract(typeof(Exception)); Assert.IsFalse(objectContract.Properties.Contains("TargetSite")); #else diff --git a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs index 3c1370642..2582f43a3 100644 --- a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs @@ -30,7 +30,7 @@ using System.Globalization; using System.IO; using Newtonsoft.Json.Schema; -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Runtime.Serialization; @@ -1139,7 +1139,7 @@ public void MaximumDateTimeMicrosoftDateFormatLength() writer.Flush(); } -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void IntegerLengthOverflows() { diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingAsyncTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingAsyncTests.cs index fa2d9a500..91f8aa7fb 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingAsyncTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingAsyncTests.cs @@ -27,7 +27,7 @@ using System; using System.Globalization; -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -593,7 +593,7 @@ await ExceptionAssert.ThrowsAsync(async () => } } -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task ReadInt64OverflowAsync() { diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingTests.cs index da47b2f65..0c82347d0 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ExceptionHandlingTests.cs @@ -28,7 +28,7 @@ using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json.Linq; -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -617,7 +617,7 @@ public void ReadInt32Overflow_Negative() } } -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ReadInt64Overflow() { @@ -639,7 +639,7 @@ public void ReadInt64Overflow() } #endif -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ReadInt64Overflow_Negative() { diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/FloatTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/FloatTests.cs index 20d4c5eac..05874fe03 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/FloatTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/FloatTests.cs @@ -28,7 +28,7 @@ using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json.Linq; -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/MiscTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/MiscTests.cs index f25590e7f..ea46f8faa 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/MiscTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/MiscTests.cs @@ -28,7 +28,7 @@ using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json.Linq; -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ParseAsyncTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ParseAsyncTests.cs index 2d61a6b9f..94a108875 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ParseAsyncTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ParseAsyncTests.cs @@ -200,7 +200,7 @@ public async Task ParseDoublesAsync() Assert.AreEqual(Double.MinValue, reader.Value); reader = new JsonTextReader(new StringReader("1E+309")); -#if !(NETSTANDARD2_0 || NETSTANDARD1_3) +#if !(NETSTANDARD2_0 || NETSTANDARD1_3 || NET6_0_OR_GREATER) await ExceptionAssert.ThrowsAsync(async () => await reader.ReadAsync(), "Input string '1E+309' is not a valid number. Path '', line 1, position 6."); #else Assert.IsTrue(await reader.ReadAsync()); @@ -209,7 +209,7 @@ public async Task ParseDoublesAsync() #endif reader = new JsonTextReader(new StringReader("-1E+5000")); -#if !(NETSTANDARD2_0 || NETSTANDARD1_3) +#if !(NETSTANDARD2_0 || NETSTANDARD1_3 || NET6_0_OR_GREATER) await ExceptionAssert.ThrowsAsync(async () => await reader.ReadAsync(), "Input string '-1E+5000' is not a valid number. Path '', line 1, position 8."); #else Assert.IsTrue(await reader.ReadAsync()); diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ParseTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ParseTests.cs index 0347a2ad2..8347f9445 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ParseTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ParseTests.cs @@ -28,7 +28,7 @@ using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json.Linq; -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -220,7 +220,7 @@ public void ParseDoubles() Assert.AreEqual(Double.MinValue, reader.Value); reader = new JsonTextReader(new StringReader("1E+309")); -#if !(NETSTANDARD2_0 || NETSTANDARD1_3) +#if !(NETSTANDARD2_0 || NETSTANDARD1_3 || NET6_0_OR_GREATER) ExceptionAssert.Throws(() => reader.Read(), "Input string '1E+309' is not a valid number. Path '', line 1, position 6."); #else Assert.IsTrue(reader.Read()); @@ -229,7 +229,7 @@ public void ParseDoubles() #endif reader = new JsonTextReader(new StringReader("-1E+5000")); -#if !(NETSTANDARD2_0 || NETSTANDARD1_3) +#if !(NETSTANDARD2_0 || NETSTANDARD1_3 || NET6_0_OR_GREATER) ExceptionAssert.Throws(() => reader.Read(), "Input string '-1E+5000' is not a valid number. Path '', line 1, position 8."); #else Assert.IsTrue(reader.Read()); diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadAsyncTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadAsyncTests.cs index 770b77363..5a99dd124 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadAsyncTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadAsyncTests.cs @@ -28,7 +28,7 @@ using System; using System.Globalization; using Newtonsoft.Json.Linq; -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -89,7 +89,7 @@ await ExceptionAssert.ThrowsAsync( ); } -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task ReadAsInt32Async_BigIntegerValue_Success() { @@ -132,7 +132,7 @@ await ExceptionAssert.ThrowsAsync(async () => "Unexpected character encountered while parsing value: u. Path '', line 1, position 1."); } -#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task ReadAsBooleanAsync() { @@ -1245,7 +1245,7 @@ second line third line", jsonTextReader.Value); } -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task ReadBigIntegerAsync() { diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadTests.cs index 5a8bd1af1..c682bcc56 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTests/ReadTests.cs @@ -28,7 +28,7 @@ using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json.Linq; -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -94,7 +94,7 @@ public void ReadAsDecimal_IntegerTooLarge_ThrowsJsonReaderException() ); } -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ReadAsInt32_BigIntegerValue_Success() { @@ -137,7 +137,7 @@ public void ReadAsInt32WithUndefined() "Unexpected character encountered while parsing value: u. Path '', line 1, position 1."); } -#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ReadAsBoolean() { @@ -1264,7 +1264,7 @@ second line -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ReadBigInteger() { diff --git a/Src/Newtonsoft.Json.Tests/JsonTextWriterAsyncTests.cs b/Src/Newtonsoft.Json.Tests/JsonTextWriterAsyncTests.cs index f61d7e5e5..d4b93cfb3 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextWriterAsyncTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextWriterAsyncTests.cs @@ -102,7 +102,7 @@ private async Task DoDelay(Task t) } } -#if !(NETSTANDARD1_0 || PORTABLE) || NETSTANDARD2_0 +#if !(NETSTANDARD1_0 || PORTABLE) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task WriteLazy() { @@ -370,7 +370,7 @@ public async Task CloseOutputAsync() Assert.IsTrue(ms.CanRead); } -#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task WriteIConvertableAsync() { @@ -1018,7 +1018,7 @@ public async Task WriteFloatingPointNumberAsync() await jsonWriter.WriteEndArrayAsync(); } -#if !(NETSTANDARD2_0 || NETSTANDARD1_3) +#if !(NETSTANDARD2_0 || NETSTANDARD1_3 || NET6_0_OR_GREATER) Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); #else Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,5E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); diff --git a/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs b/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs index f0c462337..dcab597d8 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs @@ -136,7 +136,7 @@ public void BufferTest_WithError() Assert.AreEqual(1, arrayPool.FreeArrays.Count); } -#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void BufferErroringWithInvalidSize() { @@ -225,7 +225,7 @@ public void CloseOutput() Assert.IsTrue(ms.CanRead); } -#if !(PORTABLE) || NETSTANDARD2_0 +#if !(PORTABLE) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void WriteIConvertable() { @@ -880,7 +880,7 @@ public void WriteFloatingPointNumber() jsonWriter.WriteEndArray(); } -#if !(NETSTANDARD2_0 || NETSTANDARD1_3) +#if !(NETSTANDARD2_0 || NETSTANDARD1_3 || NET6_0_OR_GREATER) Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); #else Assert.AreEqual(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,5E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); diff --git a/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs b/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs index 33b607109..522429aed 100644 --- a/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs +++ b/Src/Newtonsoft.Json.Tests/JsonValidatingReaderTests.cs @@ -30,7 +30,7 @@ #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #endif -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -353,7 +353,7 @@ public void IntegerGreaterThanMaximumValue() Assert.IsNotNull(validationEventArgs); } -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void IntegerGreaterThanMaximumValue_BigInteger() { @@ -606,7 +606,7 @@ public void FloatDivisibleBy() Assert.IsNotNull(validationEventArgs); } -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void BigIntegerDivisibleBy_Success() { diff --git a/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/JPropertyDescriptorTests.cs b/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/JPropertyDescriptorTests.cs index bcbf661e4..72bea0682 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/JPropertyDescriptorTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/ComponentModel/JPropertyDescriptorTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; diff --git a/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs b/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs index 0766b88dc..249147117 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs @@ -29,7 +29,7 @@ using System.Collections.Generic; using System.Dynamic; using System.Linq; -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -257,7 +257,7 @@ public void JValueEquals() new JProperty("Uri", new Uri("http://json.codeplex.com/")), new JProperty("Guid", new Guid("EA27FE1D-0D80-44F2-BF34-4654156FA7AF")), new JProperty("TimeSpan", TimeSpan.FromDays(1)) -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER , new JProperty("BigInteger", BigInteger.Parse("1")) #endif ); @@ -290,7 +290,7 @@ public void JValueEquals() Assert.IsTrue(d.Decimal == 1.1m); Assert.IsTrue(d.Decimal != 1.0f); Assert.IsTrue(d.Decimal != 1.0d); -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER Assert.IsTrue(d.Decimal > new BigInteger(0)); #endif @@ -306,11 +306,11 @@ public void JValueEquals() Assert.IsTrue(d.Float == 1.1m); Assert.IsTrue(d.Float != 1.0f); Assert.IsTrue(d.Float != 1.0d); -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER Assert.IsTrue(d.Float > new BigInteger(0)); #endif -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER Assert.IsTrue(d.BigInteger == d.BigInteger); Assert.IsTrue(d.BigInteger > 0); Assert.IsTrue(d.BigInteger > 0.0m); @@ -366,7 +366,7 @@ public void JValueAddition() new JProperty("Uri", new Uri("http://json.codeplex.com/")), new JProperty("Guid", new Guid("EA27FE1D-0D80-44F2-BF34-4654156FA7AF")), new JProperty("TimeSpan", TimeSpan.FromDays(1)) -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER , new JProperty("BigInteger", new BigInteger(100)) #endif ); @@ -445,7 +445,7 @@ public void JValueAddition() r += 2; Assert.AreEqual(null, r.Value); -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER r = d.BigInteger + null; Assert.AreEqual(null, r.Value); r += 2; @@ -524,7 +524,7 @@ public void JValueAddition() r -= 2; Assert.AreEqual(null, r.Value); -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER r = d.BigInteger - null; Assert.AreEqual(null, r.Value); r -= 2; @@ -598,7 +598,7 @@ public void JValueAddition() r *= 2; Assert.AreEqual(null, r.Value); -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER r = d.BigInteger * 1.1d; Assert.AreEqual(100m, (decimal)r); r *= 2; @@ -672,7 +672,7 @@ public void JValueAddition() r /= 2; Assert.AreEqual(null, r.Value); -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER r = d.BigInteger / 1.1d; Assert.AreEqual(100m, (decimal)r); r /= 2; @@ -700,7 +700,7 @@ public void JValueToString() new JProperty("Uri", new Uri("http://json.codeplex.com/")), new JProperty("Guid", new Guid("EA27FE1D-0D80-44F2-BF34-4654156FA7AF")), new JProperty("TimeSpan", TimeSpan.FromDays(1)) -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER , new JProperty("BigInteger", new BigInteger(100)) #endif ); @@ -717,7 +717,7 @@ public void JValueToString() Assert.AreEqual("http://json.codeplex.com/", d.Uri.ToString()); Assert.AreEqual("ea27fe1d-0d80-44f2-bf34-4654156fa7af", d.Guid.ToString()); Assert.AreEqual("1.00:00:00", d.TimeSpan.ToString()); -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER Assert.AreEqual("100", d.BigInteger.ToString()); #endif } @@ -801,7 +801,7 @@ public void JValueConvert() AssertValueConverted(null); AssertValueConverted(new Uri("http://json.codeplex.com/")); AssertValueConverted(null); -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER AssertValueConverted(new BigInteger(100)); AssertValueConverted(null); #endif diff --git a/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs index 1f35f666e..2cb76c50a 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs @@ -447,7 +447,7 @@ public void Iterate() } } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ITypedListGetItemProperties() { diff --git a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs index 47d7a078f..94ab0ebed 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs @@ -58,7 +58,7 @@ namespace Newtonsoft.Json.Tests.Linq [TestFixture] public class JObjectTests : TestFixtureBase { -#if !(NET35 || NET20 || PORTABLE40) || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void EmbedJValueStringInNewJObject() { @@ -743,7 +743,7 @@ public void ReplaceJPropertyWithJPropertyWithSameName() Assert.AreEqual(p4, l[1]); } -#if !(NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void PropertyChanging() { @@ -1286,7 +1286,7 @@ public void GenericListJTokenSetItemAlreadyExists() }, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void IBindingListSortDirection() { @@ -1481,7 +1481,7 @@ public void ListChanged() } #endif -#if !(NET20 || NET35 || PORTABLE40) || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void CollectionChanged() { @@ -1658,7 +1658,7 @@ public void ParseMultipleProperties_ReplaceDuplicateSetting() Assert.AreEqual("Name2", value); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void WriteObjectNullDBNullValue() { @@ -1770,7 +1770,7 @@ public void LoadFromNestedObjectIncomplete() }, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 14."); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void GetProperties() { @@ -2095,7 +2095,7 @@ public void Parse_ExcessiveContent() "Additional text encountered after finished reading JSON content: [. Path '', line 3, position 0."); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void GetPropertyOwner_ReturnsJObject() { diff --git a/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs index 64a422ee4..cb36de525 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs @@ -61,7 +61,7 @@ public void NullValue() Assert.AreEqual(p, p.Value.Parent); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ListChanged() { diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderAsyncTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderAsyncTests.cs index c394663e8..45ed6946b 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderAsyncTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderAsyncTests.cs @@ -36,7 +36,7 @@ using NUnit.Framework; #endif using System.IO; -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using Newtonsoft.Json.Linq; @@ -48,7 +48,7 @@ namespace Newtonsoft.Json.Tests.Linq [TestFixture] public class JTokenReaderAsyncTests : TestFixtureBase { -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task ConvertBigIntegerToDoubleAsync() { @@ -757,7 +757,7 @@ public async Task ReadAsDouble_Integer_SuccessAsync() Assert.AreEqual(1d, await reader.ReadAsDoubleAsync()); } -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task ReadAsBoolean_BigInteger_SuccessAsync() { diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs index 85c4feeaf..770c6b3a7 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs @@ -35,7 +35,7 @@ #endif using Newtonsoft.Json; using System.IO; -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using Newtonsoft.Json.Linq; @@ -47,7 +47,7 @@ namespace Newtonsoft.Json.Tests.Linq [TestFixture] public class JTokenReaderTest : TestFixtureBase { -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ConvertBigIntegerToDouble() { @@ -884,7 +884,7 @@ public void ReadAsDouble_Integer_Success() Assert.AreEqual(1d, reader.ReadAsDouble()); } -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ReadAsBoolean_BigInteger_Success() { diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs index 0b3fe1681..84528822e 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs @@ -25,7 +25,7 @@ using System; using System.Collections.Generic; -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -391,7 +391,7 @@ public void Casting() Assert.AreEqual(5, (int)(new JValue(StringComparison.OrdinalIgnoreCase))); -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER string bigIntegerText = "1234567899999999999999999999999999999999999999999999999999999999999990"; Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(BigInteger.Parse(bigIntegerText))).Value); @@ -472,7 +472,7 @@ public void FailedCasting() #endif ExceptionAssert.Throws(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri."); -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER ExceptionAssert.Throws(() => { var i = (new JValue(new Uri("http://www.google.com"))).ToObject(); }, "Can not convert Uri to BigInteger."); ExceptionAssert.Throws(() => { var i = (JValue.CreateNull()).ToObject(); }, "Can not convert Null to BigInteger."); ExceptionAssert.Throws(() => { var i = (new JValue(Guid.NewGuid())).ToObject(); }, "Can not convert Guid to BigInteger."); @@ -489,7 +489,7 @@ public void FailedCasting() [Test] public void ToObject() { -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger)))); Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger?)))); Assert.AreEqual((BigInteger?)null, (JValue.CreateNull().ToObject(typeof(BigInteger?)))); @@ -548,7 +548,7 @@ public void ImplicitCastingTo() Assert.IsTrue(JToken.DeepEquals(new JValue((DateTimeOffset?)null), (JValue)(DateTimeOffset?)null)); #endif -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER // had to remove implicit casting to avoid user reference to System.Numerics.dll Assert.IsTrue(JToken.DeepEquals(new JValue(new BigInteger(1)), new JValue(new BigInteger(1)))); Assert.IsTrue(JToken.DeepEquals(new JValue((BigInteger?)null), new JValue((BigInteger?)null))); @@ -1172,7 +1172,7 @@ public void DeepClone() Assert.IsTrue(a.DeepEquals(a2)); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void Clone() { diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterAsyncTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterAsyncTests.cs index 92e242376..a87ae5e78 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterAsyncTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterAsyncTests.cs @@ -26,7 +26,7 @@ #if !(NET20 || NET35 || NET40 || PORTABLE40) using System; -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -115,7 +115,7 @@ public async Task StateAsync() await jsonWriter.WriteValueAsync("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER await jsonWriter.WriteValueAsync(new BigInteger(123)); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); #endif @@ -167,7 +167,7 @@ public async Task CurrentTokenAsync() Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken); -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER await jsonWriter.WriteValueAsync(new BigInteger(123)); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken); @@ -200,7 +200,7 @@ public async Task WriteCommentAsync() /*fail*/]", writer.Token.ToString()); } -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task WriteBigIntegerAsync() { diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterTest.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterTest.cs index 18d195eb5..3c3df235c 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterTest.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterTest.cs @@ -25,7 +25,7 @@ using System; using System.Collections.Generic; -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -120,7 +120,7 @@ public void State() jsonWriter.WriteValue("DVD read/writer"); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER jsonWriter.WriteValue(new BigInteger(123)); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); #endif @@ -172,7 +172,7 @@ public void CurrentToken() Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken); -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER jsonWriter.WriteValue(new BigInteger(123)); Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken); @@ -205,7 +205,7 @@ public void WriteComment() /*fail*/]", writer.Token.ToString()); } -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void WriteBigInteger() { diff --git a/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs index 57add05ef..4eae2611d 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs @@ -28,7 +28,7 @@ using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json.Tests.TestObjects; -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Text; @@ -179,7 +179,7 @@ public void ChangeValue() Assert.AreEqual(g, v.Value); Assert.AreEqual(JTokenType.Guid, v.Type); -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER BigInteger i = BigInteger.Parse("123456789999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990"); v.Value = i; Assert.AreEqual(i, v.Value); @@ -239,13 +239,13 @@ public void JValueToString() v = new JValue(new Guid("B282ADE7-C520-496C-A448-4084F6803DE5")); Assert.AreEqual("b282ade7-c520-496c-a448-4084f6803de5", v.ToString(null, CultureInfo.InvariantCulture)); -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER v = new JValue(BigInteger.Parse("123456789999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990")); Assert.AreEqual("123456789999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990", v.ToString(null, CultureInfo.InvariantCulture)); #endif } -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void JValueParse() { @@ -256,7 +256,7 @@ public void JValueParse() } #endif -#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void JValueIConvertable() { @@ -505,7 +505,7 @@ public void ReadDatesAsDateTimeOffsetViaJsonConvert() } #endif -#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ConvertsToBoolean() { @@ -524,7 +524,7 @@ public void ConvertsToInt32() Assert.AreEqual(Int32.MaxValue, Convert.ToInt32(new JValue(Int32.MaxValue))); } -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ConvertsToInt32_BigInteger() { @@ -686,7 +686,7 @@ public void GetTypeCode() v = new JValue(new Uri("http://www.google.com")); Assert.AreEqual(TypeCode.Object, v.GetTypeCode()); -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER v = new JValue(new BigInteger(3)); Assert.AreEqual(TypeCode.Object, v.GetTypeCode()); #endif @@ -705,7 +705,7 @@ public void ToType() int i = (int)v.ToType(typeof(int), CultureInfo.InvariantCulture); Assert.AreEqual(9, i); -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER BigInteger bi = (BigInteger)v.ToType(typeof(BigInteger), CultureInfo.InvariantCulture); Assert.AreEqual(new BigInteger(9), bi); #endif @@ -720,7 +720,7 @@ public void ToStringFormat() Assert.AreEqual("2013", v.ToString("yyyy")); } -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ToStringNewTypes() { diff --git a/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathExecuteTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathExecuteTests.cs index 10611fed8..81ec02411 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathExecuteTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JsonPath/JPathExecuteTests.cs @@ -26,7 +26,7 @@ using System; using System.Collections.Generic; using System.Text; -#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using Newtonsoft.Json.Linq.JsonPath; @@ -981,7 +981,7 @@ public void LesserQuery_ValueFirst() Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1])); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void GreaterQueryBigInteger() { diff --git a/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs b/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs index c3e706545..d22262023 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs @@ -62,7 +62,7 @@ public void EscapedQuotePath() Assert.AreEqual(@"['We\'re offline!']", v.Path); } -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER public class DemoClass { public decimal maxValue; diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj index d716b0a87..49d267ffa 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -148,7 +148,7 @@ Json.NET Tests .NET 6.0 net6.0 - NETSTANDARD2_0;DNXCORE50;PORTABLE;HAVE_BENCHMARKS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) + NET6_0;DNXCORE50;PORTABLE;HAVE_BENCHMARKS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) diff --git a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs index bf8d5b1b8..d2c6fb656 100644 --- a/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs +++ b/Src/Newtonsoft.Json.Tests/Schema/JsonSchemaGeneratorTests.cs @@ -312,7 +312,7 @@ public void GenerateSchemaForType() Assert.IsTrue(v.IsValid(schema)); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void GenerateSchemaForISerializable() { @@ -340,7 +340,7 @@ public void GenerateSchemaForDBNull() } #endif -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER public class CustomDirectoryInfoMapper : DefaultContractResolver { public CustomDirectoryInfoMapper() @@ -376,7 +376,7 @@ public void GenerateSchemaCamelCase() generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; generator.ContractResolver = new CamelCasePropertyNamesContractResolver() { -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER IgnoreSerializableAttribute = true #endif }; @@ -421,7 +421,7 @@ public void GenerateSchemaCamelCase() }", json); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void GenerateSchemaSerializable() { @@ -734,7 +734,7 @@ public class BulkInsertTask_DSL { } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Serializable] public sealed class SerializableTestObject { diff --git a/Src/Newtonsoft.Json.Tests/Serialization/CamelCasePropertyNamesContractResolverTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/CamelCasePropertyNamesContractResolverTests.cs index a96adcb0d..7346ef077 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/CamelCasePropertyNamesContractResolverTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/CamelCasePropertyNamesContractResolverTests.cs @@ -119,7 +119,7 @@ public void JTokenWriter() string json = o.ToString(); } -#if !(PORTABLE || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER #pragma warning disable 618 [Test] public void MemberSearchFlags() diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs index 35e1e54c8..7e4710e86 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs @@ -118,7 +118,7 @@ public class AddressWithDataMember [TestFixture] public class ContractResolverTests : TestFixtureBase { -#if !(PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ResolveSerializableContract() { @@ -585,7 +585,7 @@ public void SingleTypeWithMultipleContractResolvers() }", startingWithB); } -#if !(PORTABLE || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER #pragma warning disable 618 [Test] public void SerializeCompilerGeneratedMembers() diff --git a/Src/Newtonsoft.Json.Tests/Serialization/DependencyInjectionTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/DependencyInjectionTests.cs index 959a9975a..dad1bb804 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/DependencyInjectionTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/DependencyInjectionTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET40 || NET35 || NET20 || DNXCORE50 || PORTABLE || PORTABLE40) || NETSTANDARD1_0 || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET40 || NET35 || NET20 || DNXCORE50 || PORTABLE || PORTABLE40) || NETSTANDARD1_0 || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using Autofac; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; diff --git a/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs index 37cfb3672..b84585403 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs @@ -101,7 +101,7 @@ public void SerializeDynamicObject() Assert.AreEqual(dynamicObject.ChildObject.Text, d.ChildObject.Text); } -#if !(PORTABLE || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeDynamicObjectWithObjectTracking() { diff --git a/Src/Newtonsoft.Json.Tests/Serialization/FSharpTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/FSharpTests.cs index 10192bd72..e399ecd5f 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/FSharpTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/FSharpTests.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET40 || NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET40 || NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs index ab790c4b6..56991bc68 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs @@ -61,7 +61,7 @@ namespace Newtonsoft.Json.Tests.Serialization [TestFixture] public class JsonSerializerCollectionsTests : TestFixtureBase { -#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeNonGenericListTypeAndReadOnlyListViaConstructor() { @@ -187,7 +187,7 @@ public void FloatKey_MaxValue() { Dictionary dictionary = new Dictionary { { float.MaxValue, 1 } }; string output = JsonConvert.SerializeObject(dictionary); -#if !(NETSTANDARD2_0 || NETSTANDARD1_3) +#if !(NETSTANDARD2_0 || NETSTANDARD1_3 || NET6_0_OR_GREATER) Assert.AreEqual(@"{""3.40282347E+38"":1}", output); #else Assert.AreEqual(@"{""3.4028235E+38"":1}", output); @@ -303,7 +303,7 @@ public void CollectionJsonConstructorBadIEnumerableParameter() "Constructor for 'Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+TestCollectionBadIEnumerableParameter' must have no parameters or a single parameter that implements 'System.Collections.Generic.IEnumerable`1[System.Int32]'."); } -#if !(DNXCORE50 || PORTABLE) || NETSTANDARD2_0 +#if !(DNXCORE50 || PORTABLE) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class TestCollectionNonGeneric : ArrayList { [JsonConstructor] @@ -416,7 +416,7 @@ public void DictionaryJsonConstructorBadIEnumerableParameter() "Constructor for 'Newtonsoft.Json.Tests.Serialization.JsonSerializerCollectionsTests+TestDictionaryBadIEnumerableParameter' must have no parameters or a single parameter that implements 'System.Collections.Generic.IEnumerable`1[System.Collections.Generic.KeyValuePair`2[System.String,System.Int32]]'."); } -#if !(DNXCORE50 || PORTABLE) || NETSTANDARD2_0 +#if !(DNXCORE50 || PORTABLE) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class TestDictionaryNonGeneric : Hashtable { [JsonConstructor] @@ -439,7 +439,7 @@ public void DictionaryJsonConstructorNonGeneric() } #endif -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class NameValueCollectionTestClass { public NameValueCollection Collection { get; set; } @@ -454,7 +454,7 @@ public void DeserializeNameValueCollection() } #endif -#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class SomeObject { public string Text1 { get; set; } @@ -1096,7 +1096,7 @@ public void NullableValueGenericDictionary() Assert.AreEqual(3, v2["Third"]); } -#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeConcurrentDictionary() { @@ -1810,7 +1810,7 @@ public void ComplexValuesInObjectArray() Assert.AreEqual(1, (int)((JObject)o.Data[2])["one"]); } -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeArrayAsArrayList() { @@ -2075,7 +2075,7 @@ public void ReadOnlyIntegerList() } #endif -#if !DNXCORE50 || NETSTANDARD2_0 +#if !DNXCORE50 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void EmptyStringInHashtableIsDeserialized() { diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs index b0d3a18a6..35e885258 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs @@ -29,10 +29,10 @@ using System.Collections.Concurrent; #endif using System.Collections.Generic; -#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif -#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.ComponentModel.DataAnnotations; using System.Configuration; using System.Runtime.CompilerServices; @@ -221,7 +221,7 @@ public void DeserializeGenericIEnumerableWithImplicitConversion() Assert.AreEqual("def", enumerableObject[1].Value); } -#if !(PORTABLE || PORTABLE40 || NET20 || NET35) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || NET20 || NET35) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void LargeIntegerAsString() { @@ -277,7 +277,7 @@ public void DeserializeBoolean_EmptyString() @"Error converting value {null} to type 'System.Boolean'. Path '[0]', line 1, position 3."); } -#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeBooleans() { @@ -742,7 +742,7 @@ public void DeserializeNullToJTokenProperty() Assert.IsNull(otc.Value5); } -#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ReadIntegerWithError() { @@ -999,7 +999,7 @@ public void JsonSerializerProperties() serializer.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor; Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializer.ConstructorHandling); -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER serializer.Context = new StreamingContext(StreamingContextStates.Other); Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializer.Context); #endif @@ -1070,7 +1070,7 @@ public void JsonSerializerProperties() serializer.TraceWriter = traceWriter; Assert.AreEqual(traceWriter, serializer.TraceWriter); -#if !(PORTABLE || PORTABLE40 || NET20 || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || NET20 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER #pragma warning disable 618 serializer.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full; Assert.AreEqual(FormatterAssemblyStyle.Full, serializer.TypeNameAssemblyFormat); @@ -1113,7 +1113,7 @@ public void JsonSerializerSettingsProperties() settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor; Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, settings.ConstructorHandling); -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER settings.Context = new StreamingContext(StreamingContextStates.Other); Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), settings.Context); #endif @@ -1190,7 +1190,7 @@ public void JsonSerializerSettingsProperties() settings.TraceWriter = traceWriter; Assert.AreEqual(traceWriter, settings.TraceWriter); -#if !(PORTABLE || PORTABLE40 || NET20 || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || NET20 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER #pragma warning disable 618 settings.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full; Assert.AreEqual(FormatterAssemblyStyle.Full, settings.TypeNameAssemblyFormat); @@ -1244,7 +1244,7 @@ public void JsonSerializerProxyProperties() serializerProxy.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor; Assert.AreEqual(ConstructorHandling.AllowNonPublicDefaultConstructor, serializerProxy.ConstructorHandling); -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER serializerProxy.Context = new StreamingContext(StreamingContextStates.Other); Assert.AreEqual(new StreamingContext(StreamingContextStates.Other), serializerProxy.Context); #endif @@ -1315,7 +1315,7 @@ public void JsonSerializerProxyProperties() serializerProxy.TraceWriter = traceWriter; Assert.AreEqual(traceWriter, serializerProxy.TraceWriter); -#if !(PORTABLE || PORTABLE40 || NET20 || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || NET20 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER #pragma warning disable 618 serializerProxy.TypeNameAssemblyFormat = FormatterAssemblyStyle.Full; Assert.AreEqual(FormatterAssemblyStyle.Full, serializerProxy.TypeNameAssemblyFormat); @@ -1336,7 +1336,7 @@ public void JsonSerializerProxyProperties() Assert.AreEqual(TypeNameHandling.All, serializerProxy.TypeNameHandling); } -#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeISerializableIConvertible() { @@ -1818,7 +1818,7 @@ public void TestMethodExecutorObject() Assert.AreEqual(executorObject2.clientGetResultFunction, "ClientBanSubsCB"); } -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void HashtableDeserialization() { @@ -2259,7 +2259,7 @@ public void SerializeConverableObjects() string json = JsonConvert.SerializeObject(new ConverableMembers(), Formatting.Indented); string expected = null; -#if (NETSTANDARD2_0) +#if (NETSTANDARD2_0 || NET6_0_OR_GREATER) expected = @"{ ""String"": ""string"", ""Int32"": 2147483647, @@ -3475,7 +3475,7 @@ To fix this error either change the JSON to a JSON object (e.g. {""name"":""valu Path '', line 1, position 1."); } -#if !(PORTABLE || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void CannotDeserializeArrayIntoSerializable() { @@ -3589,7 +3589,7 @@ public void SerializePropertyGetError() { ContractResolver = new DefaultContractResolver { -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER IgnoreSerializableAttribute = true #endif } @@ -3606,7 +3606,7 @@ public void DeserializePropertySetError() { ContractResolver = new DefaultContractResolver { -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER IgnoreSerializableAttribute = true #endif } @@ -3623,7 +3623,7 @@ public void DeserializeEnsureTypeEmptyStringToIntError() { ContractResolver = new DefaultContractResolver { -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER IgnoreSerializableAttribute = true #endif } @@ -3640,7 +3640,7 @@ public void DeserializeEnsureTypeNullToIntError() { ContractResolver = new DefaultContractResolver { -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER IgnoreSerializableAttribute = true #endif } @@ -4102,7 +4102,7 @@ public void SerializeNonIDictionary() Assert.AreEqual("value", newModelStateDictionary["key"]); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER #if DEBUG [Test] public void SerializeISerializableInPartialTrustWithIgnoreInterface() @@ -4339,7 +4339,7 @@ public void SerializeClassWithInheritedProtectedMember() }", json); } -#if !(PORTABLE) || NETSTANDARD2_0 +#if !(PORTABLE) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeClassWithInheritedProtectedMember() { @@ -4439,7 +4439,7 @@ public void SerializeDeserializeXNodeProperties() } #endif -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeDeserializeXmlNodeProperties() { @@ -4670,7 +4670,7 @@ public void DeserializeByteArray() Assert.AreEqual(0, z[1].Prop1.Length); } -#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void StringDictionaryTest() { @@ -4915,7 +4915,7 @@ public void PrivateSetterOnBaseClassProperty() Assert.AreEqual(meh.IDontWork, "meh"); } -#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeNullableStruct() { @@ -5346,7 +5346,7 @@ public void DeserializeStringIntoNullableGuid() Assert.AreEqual(new Guid("bb2f3da7-bf79-4d14-9d54-0a1f7ff5f902"), c.clientId); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeException1() { @@ -5565,7 +5565,7 @@ public void SerializeStaticReflection() Assert.AreEqual(-3, StaticTestClass.z); } -#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeDecimalsWithCulture() { @@ -5665,7 +5665,7 @@ public void DeserializeNullInt() }, "Error converting value {null} to type 'System.Int32'. Path '[3]', line 5, position 6."); } -#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeIConvertible() { @@ -6395,7 +6395,7 @@ public void DeserializeEmptyJsonString() Assert.AreEqual("", s); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeAndDeserializeWithAttributes() { @@ -6765,7 +6765,7 @@ public void SerializeFloatingPointHandling() } #if !(NET20 || NET35 || NET40 || PORTABLE40) -#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeReadOnlyListWithBigInteger() { @@ -6823,7 +6823,7 @@ public void SerializeCustomTupleWithSerializableAttribute() Action doStuff = () => { obj = JsonConvert.DeserializeObject>(json); }; -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER doStuff(); Assert.AreEqual(500, obj.Item1); #else @@ -6854,7 +6854,7 @@ public void SerializeCustomTupleWithSerializableAttributeInPartialTrust() } #endif -#if !(PORTABLE || NET35 || NET20 || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || NET35 || NET20 || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeTupleWithSerializableAttribute() { @@ -7050,7 +7050,7 @@ public void NoConstructorReadOnlyDictionaryTest() } #endif -#if !(PORTABLE || NET35 || NET20 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || NET35 || NET20 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ReadTooLargeInteger() { @@ -7073,7 +7073,7 @@ public void SerializeStructWithSerializableAndDataContract() Assert.AreEqual(@"{""First"":""One"",""Second"":2}", json); -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER DefaultContractResolver r = new DefaultContractResolver(); r.IgnoreSerializableAttribute = false; @@ -7180,7 +7180,7 @@ public void DeserializeDecimal() Assert.AreEqual(1234567890.123456m, d); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DontSerializeStaticFields() { @@ -7204,7 +7204,7 @@ public void DontSerializeStaticFields() } #endif -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeBigInteger() { @@ -7345,7 +7345,7 @@ public void SerializeDictionaryWithStructKey() } #endif -#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD1_0 || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD1_0 || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeDictionaryWithStructKey_Custom() { @@ -7436,7 +7436,7 @@ public void DeserializeCustomReferenceResolver_ViaProvider() Assert.AreEqual(jane, john.Spouse); } -#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void TypeConverterOnInterface() { @@ -7502,7 +7502,7 @@ public void Main() ParticipantEntity deserializedProduct = JsonConvert.DeserializeObject(json); } -#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ConvertibleIdTest() { @@ -7828,7 +7828,7 @@ public void DeserializedDerivedWithPrivate() Assert.AreEqual("derived", d.DerivedProperty); } -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeNullableUnsignedLong() { @@ -7843,7 +7843,7 @@ public void DeserializeNullableUnsignedLong() } #endif -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void MailMessageConverterTest() { diff --git a/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs index ea60f8a8d..2073dbcfe 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs @@ -339,7 +339,7 @@ public void DeserializeFromJToken() Assert.IsTrue(JToken.DeepEquals(t1, t2)); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeGenericObjectListWithTypeName() { diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ReferenceLoopHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ReferenceLoopHandlingTests.cs index 6ac582cfe..eb35da396 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ReferenceLoopHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ReferenceLoopHandlingTests.cs @@ -151,7 +151,7 @@ public void SerializePropertyItemReferenceLoopHandling() }", json); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Serializable] public class MainClass : ISerializable { diff --git a/Src/Newtonsoft.Json.Tests/Serialization/ReflectionAttributeProviderTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/ReflectionAttributeProviderTests.cs index 3e913ff1b..7b9bde821 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/ReflectionAttributeProviderTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/ReflectionAttributeProviderTests.cs @@ -68,7 +68,7 @@ public ReflectionTestObject( public void GetAttributes_Property() { PropertyInfo property; -#if DNXCORE50 && !NETSTANDARD2_0 +#if DNXCORE50 && !(NETSTANDARD2_0 || NET6_0_OR_GREATER) property = Newtonsoft.Json.Utilities.TypeExtensions.GetProperty(typeof(ReflectionTestObject), "TestProperty"); #else property = typeof(ReflectionTestObject).GetProperty("TestProperty"); @@ -87,7 +87,7 @@ public void GetAttributes_Property() public void GetAttributes_Field() { FieldInfo field; -#if DNXCORE50 && !NETSTANDARD2_0 +#if DNXCORE50 && !(NETSTANDARD2_0 || NET6_0_OR_GREATER) field = (FieldInfo)Newtonsoft.Json.Utilities.TypeExtensions.GetField(typeof(ReflectionTestObject), "TestField"); #else field = typeof(ReflectionTestObject).GetField("TestField"); diff --git a/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs index b0ffd7125..727684316 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/SerializationEventAttributeTests.cs @@ -272,7 +272,7 @@ public void SerializationEventContextTestObjectSubClassTest() }", json); } -#if !(PORTABLE || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class SerializationEventContextTestObject { public string TestMember { get; set; } @@ -303,7 +303,7 @@ public void SerializationEventContextTest() } #endif -#if !(PORTABLE || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void WhenSerializationErrorDetectedBySerializer_ThenCallbackIsCalled() { diff --git a/Src/Newtonsoft.Json.Tests/Serialization/TraceWriterTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/TraceWriterTests.cs index 8d8aa65d3..86eca4375 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/TraceWriterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/TraceWriterTests.cs @@ -4,7 +4,7 @@ using System.Globalization; using System.IO; using Newtonsoft.Json.Linq; -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Numerics; #endif using System.Runtime.Serialization; @@ -121,7 +121,7 @@ public async Task DeserializedJsonWithAlreadyReadReader_Async() } #endif -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DiagnosticsTraceWriterTest() { @@ -867,7 +867,7 @@ public void DeserializeTypeName() Assert.IsTrue(traceWriter.TraceRecords[9].Message.StartsWith("Finished deserializing System.Collections.Generic.List`1[System.Object]. Path '$values'")); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void DeserializeISerializable() { @@ -891,7 +891,7 @@ public void DeserializeISerializable() Assert.IsTrue(traceWriter.TraceRecords[0].Message.StartsWith("Deserializing System.Exception using ISerializable constructor. Path ''")); Assert.AreEqual(TraceLevel.Info, traceWriter.TraceRecords[0].Level); -#if !NETSTANDARD2_0 +#if !(NETSTANDARD2_0 || NET6_0_OR_GREATER) Assert.AreEqual("Error deserializing System.Exception. Member 'ClassName' was not found. Path '', line 1, position 2.", traceWriter.TraceRecords[1].Message); #else Assert.AreEqual("Error deserializing System.Exception. Member 'Message' was not found. Path '', line 1, position 2.", traceWriter.TraceRecords[1].Message); @@ -1125,7 +1125,7 @@ public async Task TraceJsonWriterTest_WriteObjectInObjectAsync() } #endif -#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void TraceJsonWriterTest() { diff --git a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs index ccb5543cc..5ae55b99a 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs @@ -28,7 +28,7 @@ #else using System.Linq; #endif -#if !(PORTABLE || PORTABLE40) || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System.Collections.ObjectModel; #if !(NET35 || NET20) using System.Dynamic; @@ -1454,7 +1454,7 @@ public void ByteArrays() CollectionAssert.AreEquivalent(data, d); } -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ISerializableTypeNameHandlingTest() { @@ -1994,7 +1994,7 @@ public void PropertyItemTypeNameHandlingDynamic() } #endif -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeDeserialize_DictionaryContextContainsGuid_DeserializesItemAsGuid() { @@ -2423,7 +2423,7 @@ public class MyInterfaceImplementationType : IMyInterfaceType public string SomeProperty { get; set; } } -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class ParentParent { [JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)] @@ -2491,7 +2491,7 @@ public class Purchase public int Quantity { get; set; } } -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class SerializableWrapper { public object Content { get; set; } diff --git a/Src/Newtonsoft.Json.Tests/Serialization/WebApiIntegrationTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/WebApiIntegrationTests.cs index 4ab4338f2..3f6f373c7 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/WebApiIntegrationTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/WebApiIntegrationTests.cs @@ -75,7 +75,7 @@ public void SerializeSerializableType() { ContractResolver = new DefaultContractResolver { -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER IgnoreSerializableAttribute = false #endif } @@ -84,7 +84,7 @@ public void SerializeSerializableType() Assert.AreEqual(expected, json); } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeInheritedType() { @@ -114,7 +114,7 @@ public InheritedType(string protectedFieldValue) : base(protectedFieldValue) } } -#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Serializable] #else [JsonObject(MemberSerialization.Fields)] diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/AnswerFilterModel.cs b/Src/Newtonsoft.Json.Tests/TestObjects/AnswerFilterModel.cs index 501e00db9..e7b81c6f2 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/AnswerFilterModel.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/AnswerFilterModel.cs @@ -34,7 +34,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Serializable] public class AnswerFilterModel { diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/AttachmentReadConverter.cs b/Src/Newtonsoft.Json.Tests/TestObjects/AttachmentReadConverter.cs index 0f2f2ca73..ce86092ce 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/AttachmentReadConverter.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/AttachmentReadConverter.cs @@ -28,7 +28,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class AttachmentReadConverter : JsonConverter { public override bool CanConvert(Type objectType) diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/ConsoleWriter.cs b/Src/Newtonsoft.Json.Tests/TestObjects/ConsoleWriter.cs index d128c0e5e..d6e005249 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/ConsoleWriter.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/ConsoleWriter.cs @@ -27,7 +27,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [TypeConverter(typeof(MyInterfaceConverter))] internal class ConsoleWriter : IMyInterface { diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/ConverableMembers.cs b/Src/Newtonsoft.Json.Tests/TestObjects/ConverableMembers.cs index 73c194ae6..bdb835408 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/ConverableMembers.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/ConverableMembers.cs @@ -41,7 +41,7 @@ public class ConverableMembers public ulong ULong = long.MaxValue; public double Double = double.MaxValue; public float Float = float.MaxValue; -#if !(PORTABLE || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public DBNull DBNull = DBNull.Value; #endif public bool Bool = true; diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/ConvertableIntTestClass.cs b/Src/Newtonsoft.Json.Tests/TestObjects/ConvertableIntTestClass.cs index 9bc040c3b..276ad53b3 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/ConvertableIntTestClass.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/ConvertableIntTestClass.cs @@ -27,7 +27,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER public class ConvertableIntTestClass { public ConvertibleInt Integer { get; set; } diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/ConvertibleInt.cs b/Src/Newtonsoft.Json.Tests/TestObjects/ConvertibleInt.cs index 0762d31be..edbf2d784 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/ConvertibleInt.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/ConvertibleInt.cs @@ -27,7 +27,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER public struct ConvertibleInt : IConvertible { private readonly int _value; diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/CustomerDataSet.cs b/Src/Newtonsoft.Json.Tests/TestObjects/CustomerDataSet.cs index 05873fafd..e17cdf9fe 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/CustomerDataSet.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/CustomerDataSet.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(PORTABLE40 || PORTABLE || DNXCORE50) || NETSTANDARD2_0 +#if !(PORTABLE40 || PORTABLE || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Collections.Generic; using System.Text; diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/EncodingReadConverter.cs b/Src/Newtonsoft.Json.Tests/TestObjects/EncodingReadConverter.cs index 98005e347..78d2d1417 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/EncodingReadConverter.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/EncodingReadConverter.cs @@ -28,7 +28,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class EncodingReadConverter : JsonConverter { public override bool CanConvert(Type objectType) diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/GeometricForms/Shape.cs b/Src/Newtonsoft.Json.Tests/TestObjects/GeometricForms/Shape.cs index 9f6a71b23..c1d38c1bd 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/GeometricForms/Shape.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/GeometricForms/Shape.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET40 || NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET40 || NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/GeometricForms/Tags.cs b/Src/Newtonsoft.Json.Tests/TestObjects/GeometricForms/Tags.cs index 8ab1aef9c..021cc9aa0 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/GeometricForms/Tags.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/GeometricForms/Tags.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER namespace Newtonsoft.Json.Tests.TestObjects.GeometricForms { public static class Tags diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/IMyInterface.cs b/Src/Newtonsoft.Json.Tests/TestObjects/IMyInterface.cs index aeda3e84a..786080f1f 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/IMyInterface.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/IMyInterface.cs @@ -27,7 +27,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [TypeConverter(typeof(MyInterfaceConverter))] internal interface IMyInterface { diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/ListOfIds.cs b/Src/Newtonsoft.Json.Tests/TestObjects/ListOfIds.cs index d8329902a..05c03a9f8 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/ListOfIds.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/ListOfIds.cs @@ -66,7 +66,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist public override bool CanConvert(Type objectType) { -#if DNXCORE50 && !NETSTANDARD2_0 +#if DNXCORE50 && !(NETSTANDARD2_0 || NET6_0_OR_GREATER) return Newtonsoft.Json.Utilities.TypeExtensions.IsAssignableFrom(typeof(IList), objectType); #else return typeof(IList).IsAssignableFrom(objectType); diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/MailAddressReadConverter.cs b/Src/Newtonsoft.Json.Tests/TestObjects/MailAddressReadConverter.cs index 65dbf1219..206cea47c 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/MailAddressReadConverter.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/MailAddressReadConverter.cs @@ -28,7 +28,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class MailAddressReadConverter : JsonConverter { public override bool CanConvert(Type objectType) diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/Money/Currency.cs b/Src/Newtonsoft.Json.Tests/TestObjects/Money/Currency.cs index 311efc921..5f026b49b 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/Money/Currency.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/Money/Currency.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET40 || NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET40 || NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER using System; using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/Money/Tags.cs b/Src/Newtonsoft.Json.Tests/TestObjects/Money/Tags.cs index 20533c17e..dc4ce8342 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/Money/Tags.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/Money/Tags.cs @@ -23,7 +23,7 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion -#if !(NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER namespace Newtonsoft.Json.Tests.TestObjects.Money { diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/MyInterfaceConverter.cs b/Src/Newtonsoft.Json.Tests/TestObjects/MyInterfaceConverter.cs index f33a7788e..2a71266e4 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/MyInterfaceConverter.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/MyInterfaceConverter.cs @@ -35,7 +35,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER internal class MyInterfaceConverter : TypeConverter { private readonly List _writers = new List diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/NullableStructPropertyClass.cs b/Src/Newtonsoft.Json.Tests/TestObjects/NullableStructPropertyClass.cs index cf4e45e61..032f8d2fb 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/NullableStructPropertyClass.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/NullableStructPropertyClass.cs @@ -27,7 +27,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [DataContract] public class NullableStructPropertyClass { diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/PersonSerializable.cs b/Src/Newtonsoft.Json.Tests/TestObjects/PersonSerializable.cs index 9f8985f4e..2d4c0f33d 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/PersonSerializable.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/PersonSerializable.cs @@ -27,7 +27,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Serializable] public class PersonSerializable { diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/PreserveReferencesCallbackTestObject.cs b/Src/Newtonsoft.Json.Tests/TestObjects/PreserveReferencesCallbackTestObject.cs index c25c9adfd..838509c08 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/PreserveReferencesCallbackTestObject.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/PreserveReferencesCallbackTestObject.cs @@ -28,7 +28,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Serializable] public class PreserveReferencesCallbackTestObject : ISerializable { diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/Ratio.cs b/Src/Newtonsoft.Json.Tests/TestObjects/Ratio.cs index 87e1d01b9..3ae7136ad 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/Ratio.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/Ratio.cs @@ -29,7 +29,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER [Serializable] public struct Ratio : IConvertible, IFormattable, ISerializable { diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/SerializableContractResolver.cs b/Src/Newtonsoft.Json.Tests/TestObjects/SerializableContractResolver.cs index 68bdacc00..5c0539336 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/SerializableContractResolver.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/SerializableContractResolver.cs @@ -27,7 +27,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(PORTABLE || NET35 || NET20 || PORTABLE40 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(PORTABLE || NET35 || NET20 || PORTABLE40 || DNXCORE50) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER public class SerializableContractResolver : DefaultContractResolver { public SerializableContractResolver() diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/StringDictionaryTestClass.cs b/Src/Newtonsoft.Json.Tests/TestObjects/StringDictionaryTestClass.cs index 31e803bb8..682a2ab50 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/StringDictionaryTestClass.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/StringDictionaryTestClass.cs @@ -27,7 +27,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class StringDictionaryTestClass { public StringDictionary StringDictionaryProperty { get; set; } diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/StructISerializable.cs b/Src/Newtonsoft.Json.Tests/TestObjects/StructISerializable.cs index 7d2d2a66a..f20092721 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/StructISerializable.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/StructISerializable.cs @@ -27,7 +27,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 +#if !(NET20 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [DataContract] public struct StructISerializable : ISerializable { diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/TraceWriter.cs b/Src/Newtonsoft.Json.Tests/TestObjects/TraceWriter.cs index bfaf00fc4..1add12e86 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/TraceWriter.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/TraceWriter.cs @@ -25,7 +25,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER internal class TraceWriter : IMyInterface { public string Name diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/TypeConverterJsonConverter.cs b/Src/Newtonsoft.Json.Tests/TestObjects/TypeConverterJsonConverter.cs index 9a8d65159..5ad4907f9 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/TypeConverterJsonConverter.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/TypeConverterJsonConverter.cs @@ -34,7 +34,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 +#if !(NET35 || NET20 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER internal class TypeConverterJsonConverter : JsonConverter { private TypeConverter GetConverter(Type type) diff --git a/Src/Newtonsoft.Json.Tests/TestObjects/TypedSubHashtable.cs b/Src/Newtonsoft.Json.Tests/TestObjects/TypedSubHashtable.cs index 35581a304..d88b75ae3 100644 --- a/Src/Newtonsoft.Json.Tests/TestObjects/TypedSubHashtable.cs +++ b/Src/Newtonsoft.Json.Tests/TestObjects/TypedSubHashtable.cs @@ -27,7 +27,7 @@ namespace Newtonsoft.Json.Tests.TestObjects { -#if !(DNXCORE50) || NETSTANDARD2_0 +#if !(DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER public class TypedSubHashtable { public string Name; diff --git a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index 864697f07..dd6477e34 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -1405,7 +1405,7 @@ protected virtual IValueProvider CreateMemberValueProvider(MemberInfo member) // warning - this method use to cause errors with Intellitrace. Retest in VS Ultimate after changes IValueProvider valueProvider; -#if !(PORTABLE40 || PORTABLE || DOTNET || NETSTANDARD2_0) +#if !(PORTABLE40 || PORTABLE || DOTNET || NETSTANDARD2_0 || NET6_0_OR_GREATER) if (DynamicCodeGeneration) { valueProvider = new DynamicValueProvider(member); From f0dcd5b434371bcc59fcb4150979ce35a6a9338d Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Mon, 16 May 2022 21:02:57 +0800 Subject: [PATCH 18/30] Add support for DateOnly and TimeOnly (#2679) --- .../Serialization/DateOnlyTests.cs | 203 +++++++++++++++++ .../Serialization/TimeOnlyTests.cs | 212 ++++++++++++++++++ Src/Newtonsoft.Json/Newtonsoft.Json.csproj | 2 +- .../Serialization/DefaultContractResolver.cs | 7 + .../JsonSerializerInternalWriter.cs | 13 ++ Src/Newtonsoft.Json/Utilities/ConvertUtils.cs | 12 + 6 files changed, 448 insertions(+), 1 deletion(-) create mode 100644 Src/Newtonsoft.Json.Tests/Serialization/DateOnlyTests.cs create mode 100644 Src/Newtonsoft.Json.Tests/Serialization/TimeOnlyTests.cs diff --git a/Src/Newtonsoft.Json.Tests/Serialization/DateOnlyTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/DateOnlyTests.cs new file mode 100644 index 000000000..5d84052e0 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Serialization/DateOnlyTests.cs @@ -0,0 +1,203 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +#if NET6_0_OR_GREATER +using System; +using System.Collections.Generic; +#if !NET20 +using System.Xml.Linq; +#endif +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +using Xunit.Abstractions; +#else +using NUnit.Framework; +#endif + +namespace Newtonsoft.Json.Tests.Serialization +{ + [TestFixture] + public class DateOnlyTests : TestFixtureBase + { + [Test] + public void Serialize() + { + DateOnly d = new DateOnly(2000, 12, 29); + string json = JsonConvert.SerializeObject(d, Formatting.Indented); + + Assert.AreEqual(@"""2000-12-29""", json); + } + + [Test] + public void SerializeDefault() + { + DateOnly d = default; + string json = JsonConvert.SerializeObject(d, Formatting.Indented); + + Assert.AreEqual(@"""0001-01-01""", json); + } + + [Test] + public void SerializeMaxValue() + { + DateOnly d = DateOnly.MaxValue; + string json = JsonConvert.SerializeObject(d, Formatting.Indented); + + Assert.AreEqual(@"""9999-12-31""", json); + } + + [Test] + public void SerializeMinValue() + { + DateOnly d = DateOnly.MinValue; + string json = JsonConvert.SerializeObject(d, Formatting.Indented); + + Assert.AreEqual(@"""0001-01-01""", json); + } + + [Test] + public void SerializeNullable_Null() + { + DateOnly? d = default; + string json = JsonConvert.SerializeObject(d, Formatting.Indented); + + Assert.AreEqual("null", json); + } + + [Test] + public void SerializeNullable_Value() + { + DateOnly? d = new DateOnly(2000, 12, 29); + string json = JsonConvert.SerializeObject(d, Formatting.Indented); + + Assert.AreEqual(@"""2000-12-29""", json); + } + + [Test] + public void SerializeList() + { + IList d = new List + { + new DateOnly(2000, 12, 29) + }; + string json = JsonConvert.SerializeObject(d, Formatting.Indented); + + Assert.AreEqual(@"[ + ""2000-12-29"" +]", json); + } + + [Test] + public void SerializeList_Nullable() + { + IList d = new List + { + new DateOnly(2000, 12, 29), + null + }; + string json = JsonConvert.SerializeObject(d, Formatting.Indented); + + Assert.AreEqual(@"[ + ""2000-12-29"", + null +]", json); + } + + [Test] + public void Deserialize() + { + DateOnly d = JsonConvert.DeserializeObject(@"""2000-12-29"""); + + Assert.AreEqual(new DateOnly(2000, 12, 29), d); + } + + [Test] + public void DeserializeDefault() + { + DateOnly d = JsonConvert.DeserializeObject(@"""0001-01-01"""); + + Assert.AreEqual(default(DateOnly), d); + } + + [Test] + public void DeserializeMaxValue() + { + DateOnly d = JsonConvert.DeserializeObject(@"""9999-12-31"""); + + Assert.AreEqual(DateOnly.MaxValue, d); + } + + [Test] + public void DeserializeMinValue() + { + DateOnly d = JsonConvert.DeserializeObject(@"""0001-01-01"""); + + Assert.AreEqual(DateOnly.MinValue, d); + } + + [Test] + public void DeserializeNullable_Null() + { + DateOnly? d = JsonConvert.DeserializeObject(@"null"); + + Assert.AreEqual(null, d); + } + + [Test] + public void DeserializeNullable_Value() + { + DateOnly? d = JsonConvert.DeserializeObject(@"""2000-12-29"""); + + Assert.AreEqual(new DateOnly(2000, 12, 29), d); + } + + [Test] + public void DeserializeList() + { + var l = JsonConvert.DeserializeObject>(@"[ + ""2000-12-29"" +]"); + + Assert.AreEqual(1, l.Count); + Assert.AreEqual(new DateOnly(2000, 12, 29), l[0]); + } + + [Test] + public void DeserializeList_Nullable() + { + var l = JsonConvert.DeserializeObject>(@"[ + ""2000-12-29"", + null +]"); + + Assert.AreEqual(2, l.Count); + Assert.AreEqual(new DateOnly(2000, 12, 29), l[0]); + Assert.AreEqual(null, l[1]); + } + } +} +#endif diff --git a/Src/Newtonsoft.Json.Tests/Serialization/TimeOnlyTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/TimeOnlyTests.cs new file mode 100644 index 000000000..ce9c3d5f7 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Serialization/TimeOnlyTests.cs @@ -0,0 +1,212 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +#if NET6_0_OR_GREATER +using System; +using System.Collections.Generic; +#if !NET20 +using System.Xml.Linq; +#endif +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +using Xunit.Abstractions; +#else +using NUnit.Framework; +#endif + +namespace Newtonsoft.Json.Tests.Serialization +{ + [TestFixture] + public class TimeOnlyTests : TestFixtureBase + { + [Test] + public void Serialize() + { + TimeOnly t = new TimeOnly(23, 59, 59); + string json = JsonConvert.SerializeObject(t, Formatting.Indented); + + Assert.AreEqual(@"""23:59:59""", json); + } + + [Test] + public void Serialize_Milliseconds() + { + TimeOnly t = new TimeOnly(23, 59, 59, 999); + string json = JsonConvert.SerializeObject(t, Formatting.Indented); + + Assert.AreEqual(@"""23:59:59.999""", json); + } + + [Test] + public void SerializeDefault() + { + TimeOnly t = default; + string json = JsonConvert.SerializeObject(t, Formatting.Indented); + + Assert.AreEqual(@"""00:00:00""", json); + } + + [Test] + public void SerializeMaxValue() + { + TimeOnly t = TimeOnly.MaxValue; + string json = JsonConvert.SerializeObject(t, Formatting.Indented); + + Assert.AreEqual(@"""23:59:59.9999999""", json); + } + + [Test] + public void SerializeMinValue() + { + TimeOnly t = TimeOnly.MinValue; + string json = JsonConvert.SerializeObject(t, Formatting.Indented); + + Assert.AreEqual(@"""00:00:00""", json); + } + + [Test] + public void SerializeNullable_Null() + { + TimeOnly? t = default; + string json = JsonConvert.SerializeObject(t, Formatting.Indented); + + Assert.AreEqual("null", json); + } + + [Test] + public void SerializeNullable_Value() + { + TimeOnly? t = new TimeOnly(23, 59, 59, 999); + string json = JsonConvert.SerializeObject(t, Formatting.Indented); + + Assert.AreEqual(@"""23:59:59.999""", json); + } + + [Test] + public void SerializeList() + { + IList l = new List + { + new TimeOnly(23, 59, 59) + }; + string json = JsonConvert.SerializeObject(l, Formatting.Indented); + + Assert.AreEqual(@"[ + ""23:59:59"" +]", json); + } + + [Test] + public void SerializeList_Nullable() + { + IList l = new List + { + new TimeOnly(23, 59, 59), + null + }; + string json = JsonConvert.SerializeObject(l, Formatting.Indented); + + Assert.AreEqual(@"[ + ""23:59:59"", + null +]", json); + } + + [Test] + public void Deserialize() + { + TimeOnly t = JsonConvert.DeserializeObject(@"""23:59:59"""); + + Assert.AreEqual(new TimeOnly(23, 59, 59), t); + } + + [Test] + public void DeserializeDefault() + { + TimeOnly t = JsonConvert.DeserializeObject(@"""00:00:00"""); + + Assert.AreEqual(default(TimeOnly), t); + } + + [Test] + public void DeserializeMaxValue() + { + TimeOnly t = JsonConvert.DeserializeObject(@"""23:59:59.9999999"""); + + Assert.AreEqual(TimeOnly.MaxValue, t); + } + + [Test] + public void DeserializeMinValue() + { + TimeOnly t = JsonConvert.DeserializeObject(@"""00:00:00"""); + + Assert.AreEqual(TimeOnly.MinValue, t); + } + + [Test] + public void DeserializeNullable_Null() + { + TimeOnly? t = JsonConvert.DeserializeObject(@"null"); + + Assert.AreEqual(null, t); + } + + [Test] + public void DeserializeNullable_Value() + { + TimeOnly? t = JsonConvert.DeserializeObject(@"""23:59:59"""); + + Assert.AreEqual(new TimeOnly(23, 59, 59), t); + } + + [Test] + public void DeserializeList() + { + var l = JsonConvert.DeserializeObject>(@"[ + ""23:59:59"" +]"); + + Assert.AreEqual(1, l.Count); + Assert.AreEqual(new TimeOnly(23, 59, 59), l[0]); + } + + [Test] + public void DeserializeList_Nullable() + { + var l = JsonConvert.DeserializeObject>(@"[ + ""23:59:59"", + null +]"); + + Assert.AreEqual(2, l.Count); + Assert.AreEqual(new TimeOnly(23, 59, 59), l[0]); + Assert.AreEqual(null, l[1]); + } + } +} +#endif diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index 21b98b1ee..60fe7e82a 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -53,7 +53,7 @@ Json.NET .NET 6.0 - HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;$(AdditionalConstants) + HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants) Json.NET .NET 4.5 diff --git a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index dd6477e34..94bf51085 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -1292,6 +1292,13 @@ internal static bool CanConvertToString(Type type) return true; } +#if HAVE_DATE_ONLY + if (type == typeof(DateOnly) || type == typeof(TimeOnly)) + { + return true; + } +#endif + return false; } diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs index 4ea158381..7feb6ad35 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs @@ -396,6 +396,19 @@ private string GetReference(JsonWriter writer, object value) internal static bool TryConvertToString(object value, Type type, [NotNullWhen(true)]out string? s) { +#if HAVE_DATE_ONLY + if (value is DateOnly dateOnly) + { + s = dateOnly.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture); + return true; + } + if (value is TimeOnly timeOnly) + { + s = timeOnly.ToString("HH':'mm':'ss.FFFFFFF", CultureInfo.InvariantCulture); + return true; + } +#endif + #if HAVE_TYPE_DESCRIPTOR if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out TypeConverter converter)) { diff --git a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs index 9ce44964e..b6837eca9 100644 --- a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -503,6 +503,18 @@ private static ConvertResult TryConvertInternal(object? initialValue, CultureInf value = Type.GetType(s, true); return ConvertResult.Success; } +#if HAVE_DATE_ONLY + if (targetType == typeof(DateOnly)) + { + value = DateOnly.ParseExact(s, "yyyy'-'MM'-'dd", CultureInfo.InvariantCulture); + return ConvertResult.Success; + } + if (targetType == typeof(TimeOnly)) + { + value = TimeOnly.ParseExact(s, "HH':'mm':'ss.FFFFFFF", CultureInfo.InvariantCulture); + return ConvertResult.Success; + } +#endif } #if HAVE_BIG_INTEGER From e6fbab98d55e518b194dd76ad082e02e93c1db2a Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Mon, 16 May 2022 21:21:03 +0800 Subject: [PATCH 19/30] Update to 13.0.2-beta1 --- Build/build.ps1 | 2 +- Build/version.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Build/build.ps1 b/Build/build.ps1 index d5927e260..543ae9c69 100644 --- a/Build/build.ps1 +++ b/Build/build.ps1 @@ -14,7 +14,7 @@ $workingName = if ($workingName) {$workingName} else {"Working"} $assemblyVersion = if ($assemblyVersion) {$assemblyVersion} else {$majorVersion + '.0.0'} $netCliChannel = "Current" - $netCliVersion = "6.0.100" + $netCliVersion = "6.0.300" $nugetUrl = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" $ensureNetCliSdk = $true diff --git a/Build/version.json b/Build/version.json index 7e0f6ad33..1d3cc8683 100644 --- a/Build/version.json +++ b/Build/version.json @@ -1,6 +1,6 @@ { "Major": 13, "Release": 2, - "Prerelease": null, + "Prerelease": "beta1", "Assembly": null } \ No newline at end of file From 94ff24f815a777269920f5a7b13f60db50c5eeb7 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Thu, 16 Jun 2022 17:32:34 +0800 Subject: [PATCH 20/30] Fix blocking IO in JsonTextWriter.CloseAsync and add IAsyncDisposable (#2695) --- Src/Newtonsoft.Json.Tests/Issues/Issue2694.cs | 158 ++++++++++++++++++ Src/Newtonsoft.Json/JsonReader.Async.cs | 18 ++ Src/Newtonsoft.Json/JsonTextWriter.Async.cs | 29 +++- Src/Newtonsoft.Json/JsonWriter.Async.cs | 13 ++ Src/Newtonsoft.Json/Newtonsoft.Json.csproj | 2 +- 5 files changed, 218 insertions(+), 2 deletions(-) create mode 100644 Src/Newtonsoft.Json.Tests/Issues/Issue2694.cs diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2694.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2694.cs new file mode 100644 index 000000000..fbb1a947e --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2694.cs @@ -0,0 +1,158 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +#if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0 || NET6_0_OR_GREATER +using System; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#if DNXCORE50 +using System.Reflection; +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif + +namespace Newtonsoft.Json.Tests.Issues +{ + [TestFixture] + public class Issue2694 : TestFixtureBase + { +#if NET6_0_OR_GREATER + [Test] + public async Task Test_Reader_DisposeAsync() + { + JsonTextReader reader = new JsonTextReader(new StringReader("{}")); + IAsyncDisposable asyncDisposable = reader; + await asyncDisposable.DisposeAsync(); + + await ExceptionAssert.ThrowsAsync(() => reader.ReadAsync(), + "Unexpected state: Closed. Path '', line 1, position 0."); + } + + [Test] + public async Task Test_Writer_DisposeAsync() + { + MemoryStream ms = new MemoryStream(); + Stream s = new AsyncOnlyStream(ms); + StreamWriter sr = new StreamWriter(s, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), 2, leaveOpen: true); + await using (JsonTextWriter writer = new JsonTextWriter(sr)) + { + await writer.WriteStartObjectAsync(); + } + + string json = Encoding.UTF8.GetString(ms.ToArray()); + Assert.AreEqual("{}", json); + } +#endif + + [Test] + public async Task Test_Writer_CloseAsync() + { + MemoryStream ms = new MemoryStream(); + Stream s = new AsyncOnlyStream(ms); + StreamWriter sr = new StreamWriter(s, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), 2, leaveOpen: true); + JsonTextWriter writer = new JsonTextWriter(sr); + await writer.WriteStartObjectAsync(); + + await writer.CloseAsync(); + + string json = Encoding.UTF8.GetString(ms.ToArray()); + Assert.AreEqual("{}", json); + } + + public class AsyncOnlyStream : Stream + { + private readonly Stream _innerStream; + private int _unflushedContentLength; + + public AsyncOnlyStream(Stream innerStream) + { + _innerStream = innerStream; + } + + public override void Flush() + { + // It's ok to call Flush if the content was already processed with FlushAsync. + if (_unflushedContentLength > 0) + { + throw new Exception($"Flush when there is {_unflushedContentLength} bytes buffered."); + } + } + + public override Task FlushAsync(CancellationToken cancellationToken) + { + _unflushedContentLength = 0; + return _innerStream.FlushAsync(cancellationToken); + } + + public override long Seek(long offset, SeekOrigin origin) + { + return _innerStream.Seek(offset, origin); + } + + public override void SetLength(long value) + { + _innerStream.SetLength(value); + } + + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return _innerStream.ReadAsync(buffer, offset, count, cancellationToken); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + _unflushedContentLength += count; + return _innerStream.WriteAsync(buffer, offset, count, cancellationToken); + } + + public override bool CanRead => _innerStream.CanRead; + public override bool CanSeek => _innerStream.CanSeek; + public override bool CanWrite => _innerStream.CanWrite; + public override long Length => _innerStream.Length; + + public override long Position + { + get => _innerStream.Position; + set => _innerStream.Position = value; + } + } + } +} +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/JsonReader.Async.cs b/Src/Newtonsoft.Json/JsonReader.Async.cs index 024903e76..537674f19 100644 --- a/Src/Newtonsoft.Json/JsonReader.Async.cs +++ b/Src/Newtonsoft.Json/JsonReader.Async.cs @@ -34,7 +34,25 @@ namespace Newtonsoft.Json { public abstract partial class JsonReader +#if HAVE_ASYNC_DISPOABLE + : IAsyncDisposable +#endif { +#if HAVE_ASYNC_DISPOABLE + ValueTask IAsyncDisposable.DisposeAsync() + { + try + { + Dispose(true); + return default; + } + catch (Exception exc) + { + return ValueTask.FromException(exc); + } + } +#endif + /// /// Asynchronously reads the next JSON token from the source. /// diff --git a/Src/Newtonsoft.Json/JsonTextWriter.Async.cs b/Src/Newtonsoft.Json/JsonTextWriter.Async.cs index f3ac2398d..b13b6e4c9 100644 --- a/Src/Newtonsoft.Json/JsonTextWriter.Async.cs +++ b/Src/Newtonsoft.Json/JsonTextWriter.Async.cs @@ -132,7 +132,34 @@ internal async Task DoCloseAsync(CancellationToken cancellationToken) await WriteEndAsync(cancellationToken).ConfigureAwait(false); } - CloseBufferAndWriter(); + await CloseBufferAndWriterAsync().ConfigureAwait(false); + } + + private async Task CloseBufferAndWriterAsync() + { + if (_writeBuffer != null) + { + BufferUtils.ReturnBuffer(_arrayPool, _writeBuffer); + _writeBuffer = null; + } + + if (CloseOutput && _writer != null) + { +#if HAVE_ASYNC_DISPOABLE + await _writer.DisposeAsync().ConfigureAwait(false); +#else + // DisposeAsync isn't available. Instead, flush any remaining content with FlushAsync + // to prevent Close/Dispose from making a blocking flush. + // + // No cancellation token on TextWriter.FlushAsync?! + await _writer.FlushAsync().ConfigureAwait(false); +#if HAVE_STREAM_READER_WRITER_CLOSE + _writer.Close(); +#else + _writer.Dispose(); +#endif +#endif + } } /// diff --git a/Src/Newtonsoft.Json/JsonWriter.Async.cs b/Src/Newtonsoft.Json/JsonWriter.Async.cs index 4610594c3..acb7170a3 100644 --- a/Src/Newtonsoft.Json/JsonWriter.Async.cs +++ b/Src/Newtonsoft.Json/JsonWriter.Async.cs @@ -37,7 +37,20 @@ namespace Newtonsoft.Json { public abstract partial class JsonWriter +#if HAVE_ASYNC_DISPOABLE + : IAsyncDisposable +#endif { +#if HAVE_ASYNC_DISPOABLE + async ValueTask IAsyncDisposable.DisposeAsync() + { + if (_currentState != State.Closed) + { + await CloseAsync().ConfigureAwait(false); + } + } +#endif + internal Task AutoCompleteAsync(JsonToken tokenBeingWritten, CancellationToken cancellationToken) { State oldState = _currentState; diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index 60fe7e82a..d08c33e84 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -53,7 +53,7 @@ Json.NET .NET 6.0 - HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants) + HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_ASYNC_DISPOABLE;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants) Json.NET .NET 4.5 From cb9eed96665019f7398c53c540a87ce675f5d938 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Thu, 4 Aug 2022 15:02:55 +0800 Subject: [PATCH 21/30] Fix deserializing via constructor with ignored base type properties (#2711) --- Src/Newtonsoft.Json.Tests/Issues/Issue2708.cs | 81 +++++++++++++++++++ .../JsonSerializerInternalReader.cs | 7 ++ 2 files changed, 88 insertions(+) create mode 100644 Src/Newtonsoft.Json.Tests/Issues/Issue2708.cs diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2708.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2708.cs new file mode 100644 index 000000000..149544e18 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2708.cs @@ -0,0 +1,81 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +#if !NET20 +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Threading; +using Newtonsoft.Json.Linq; +#if DNXCORE50 +using System.Reflection; +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif + +namespace Newtonsoft.Json.Tests.Issues +{ + [TestFixture] + public class Issue2708 : TestFixtureBase + { + [Test] + public void Test() + { + string json = @" +{ + ""Name"": ""MyName"", + ""ChildClassProp"": ""MyValue"", +}"; + + var record = JsonConvert.DeserializeObject(json); + Assert.AreEqual(null, record.Name); // Not set because doesn't have DataMember + Assert.AreEqual("MyValue", record.ChildClassProp); + } + + [DataContract] + public abstract class RecordBase + { + [JsonExtensionData] + protected IDictionary additionalData; + + public string Name { get; set; } + } + + [DataContract] + public class MyRecord : RecordBase + { + public MyRecord(string childClassProp) => ChildClassProp = childClassProp; + + [DataMember] + public string ChildClassProp { get; set; } + } + } +} +#endif diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 4ef652b6b..d43367cc3 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -2244,6 +2244,13 @@ private List ResolvePropertyAndCreatorValues(JsonObjectC continue; } + else + { + if (!reader.Read()) + { + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + } + } } else { From b8f4ef0f980a8ee36f511cdec2feb25d5d5d0054 Mon Sep 17 00:00:00 2001 From: Eddy Nakamura Date: Mon, 29 Aug 2022 21:03:33 -0700 Subject: [PATCH 22/30] Fixing misspelling (#2698) --- Src/Newtonsoft.Json/JsonReader.Async.cs | 4 ++-- Src/Newtonsoft.Json/JsonTextWriter.Async.cs | 2 +- Src/Newtonsoft.Json/JsonWriter.Async.cs | 4 ++-- Src/Newtonsoft.Json/Newtonsoft.Json.csproj | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Src/Newtonsoft.Json/JsonReader.Async.cs b/Src/Newtonsoft.Json/JsonReader.Async.cs index 537674f19..d76c492e5 100644 --- a/Src/Newtonsoft.Json/JsonReader.Async.cs +++ b/Src/Newtonsoft.Json/JsonReader.Async.cs @@ -34,11 +34,11 @@ namespace Newtonsoft.Json { public abstract partial class JsonReader -#if HAVE_ASYNC_DISPOABLE +#if HAVE_ASYNC_DISPOSABLE : IAsyncDisposable #endif { -#if HAVE_ASYNC_DISPOABLE +#if HAVE_ASYNC_DISPOSABLE ValueTask IAsyncDisposable.DisposeAsync() { try diff --git a/Src/Newtonsoft.Json/JsonTextWriter.Async.cs b/Src/Newtonsoft.Json/JsonTextWriter.Async.cs index b13b6e4c9..097ed3c6e 100644 --- a/Src/Newtonsoft.Json/JsonTextWriter.Async.cs +++ b/Src/Newtonsoft.Json/JsonTextWriter.Async.cs @@ -145,7 +145,7 @@ private async Task CloseBufferAndWriterAsync() if (CloseOutput && _writer != null) { -#if HAVE_ASYNC_DISPOABLE +#if HAVE_ASYNC_DISPOSABLE await _writer.DisposeAsync().ConfigureAwait(false); #else // DisposeAsync isn't available. Instead, flush any remaining content with FlushAsync diff --git a/Src/Newtonsoft.Json/JsonWriter.Async.cs b/Src/Newtonsoft.Json/JsonWriter.Async.cs index acb7170a3..ffb1af826 100644 --- a/Src/Newtonsoft.Json/JsonWriter.Async.cs +++ b/Src/Newtonsoft.Json/JsonWriter.Async.cs @@ -37,11 +37,11 @@ namespace Newtonsoft.Json { public abstract partial class JsonWriter -#if HAVE_ASYNC_DISPOABLE +#if HAVE_ASYNC_DISPOSABLE : IAsyncDisposable #endif { -#if HAVE_ASYNC_DISPOABLE +#if HAVE_ASYNC_DISPOSABLE async ValueTask IAsyncDisposable.DisposeAsync() { if (_currentState != State.Closed) diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index d08c33e84..47c63018e 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -53,7 +53,7 @@ Json.NET .NET 6.0 - HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_ASYNC_DISPOABLE;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants) + HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_ASYNC_DISPOSABLE;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants) Json.NET .NET 4.5 From 4dc9af66e07dea321ad101bfb379326127251a80 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Tue, 30 Aug 2022 13:16:38 +0800 Subject: [PATCH 23/30] Add roll forward to global.json (#2726) --- Src/global.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Src/global.json b/Src/global.json index 19c87f2a5..49d225529 100644 --- a/Src/global.json +++ b/Src/global.json @@ -1,5 +1,6 @@ { "sdk": { - "version": "6.0.300" + "version": "6.0.300", + "rollForward": "latestFeature" } } From bd989708b17d5a47b43571414f69ecc0b699eccc Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Tue, 30 Aug 2022 14:09:07 +0800 Subject: [PATCH 24/30] Update to 13.0.2-beta2 --- Build/version.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Build/version.json b/Build/version.json index 1d3cc8683..69db9f005 100644 --- a/Build/version.json +++ b/Build/version.json @@ -1,6 +1,6 @@ { "Major": 13, "Release": 2, - "Prerelease": "beta1", + "Prerelease": "beta2", "Assembly": null } \ No newline at end of file From aae9284e2091e4f2409df175d273cba496c21ccc Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Tue, 30 Aug 2022 14:32:47 +0800 Subject: [PATCH 25/30] Update SDK --- Build/build.ps1 | 2 +- Src/global.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Build/build.ps1 b/Build/build.ps1 index 543ae9c69..da53db98b 100644 --- a/Build/build.ps1 +++ b/Build/build.ps1 @@ -14,7 +14,7 @@ $workingName = if ($workingName) {$workingName} else {"Working"} $assemblyVersion = if ($assemblyVersion) {$assemblyVersion} else {$majorVersion + '.0.0'} $netCliChannel = "Current" - $netCliVersion = "6.0.300" + $netCliVersion = "6.0.400" $nugetUrl = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" $ensureNetCliSdk = $true diff --git a/Src/global.json b/Src/global.json index 49d225529..18b4598f7 100644 --- a/Src/global.json +++ b/Src/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "6.0.300", + "version": "6.0.400", "rollForward": "latestFeature" } } From d0a328e8a46304d62d2174b8bba54721d02be3d3 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Tue, 13 Sep 2022 08:08:02 +0800 Subject: [PATCH 26/30] Fix MaxDepth not being used with ISerializable deserialization (#2736) --- Src/Newtonsoft.Json.Tests/Issues/Issue2735.cs | 164 ++++++++++++++++++ .../JsonSerializerInternalReader.cs | 1 + 2 files changed, 165 insertions(+) create mode 100644 Src/Newtonsoft.Json.Tests/Issues/Issue2735.cs diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2735.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2735.cs new file mode 100644 index 000000000..14a08b180 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2735.cs @@ -0,0 +1,164 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +#if !NET20 +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Tests.Documentation.Samples.Serializer; +#if DNXCORE50 +using System.Reflection; +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif + +namespace Newtonsoft.Json.Tests.Issues +{ + [TestFixture] + public class Issue2735 : TestFixtureBase + { + [Test] + public void Test() + { + int maxDepth = 512; + + var currentFoo = new Foo(null); + + for (var i = 0; i < 100; i++) + { + currentFoo = new Foo(currentFoo); + } + + var fooBar = new FooBar(); + fooBar.AddFoo("main", currentFoo); + + var json = JsonConvert.SerializeObject(fooBar, SerializeSettings(maxDepth)); + + JsonConvert.DeserializeObject(json, DeserializeSettings(maxDepth)); + } + + [Test] + public void Test_Failure() + { + int maxDepth = 512; + + var currentFoo = new Foo(null); + + for (var i = 0; i < 600; i++) + { + currentFoo = new Foo(currentFoo); + } + + var fooBar = new FooBar(); + fooBar.AddFoo("main", currentFoo); + + var json = JsonConvert.SerializeObject(fooBar, SerializeSettings(maxDepth)); + + var ex = ExceptionAssert.Throws(() => JsonConvert.DeserializeObject(json, DeserializeSettings(maxDepth))); + Assert.IsTrue(ex.Message.StartsWith("The reader's MaxDepth of 512 has been exceeded.")); + } + + [Test] + public void Test_Failure2() + { + int maxDepth = 10; + + var currentFoo = new Foo(null); + + for (var i = 0; i < 20; i++) + { + currentFoo = new Foo(currentFoo); + } + + var fooBar = new FooBar(); + fooBar.AddFoo("main", currentFoo); + + var json = JsonConvert.SerializeObject(fooBar, SerializeSettings(maxDepth)); + + var ex = ExceptionAssert.Throws(() => JsonConvert.DeserializeObject(json, DeserializeSettings(maxDepth))); + Assert.IsTrue(ex.Message.StartsWith("The reader's MaxDepth of 10 has been exceeded.")); + } + + [Serializable] + public class FooBar : ISerializable + { + private Dictionary _myData = new Dictionary(); + + public IList FooList => _myData.Values.ToList(); + + public FooBar() + { + } + + public FooBar(SerializationInfo info, StreamingContext context) + { + _myData = (Dictionary)info.GetValue(nameof(_myData), typeof(Dictionary)); + } + + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue(nameof(_myData), _myData); + } + + public void AddFoo(string name, Foo myFoo) + { + _myData[name] = myFoo; + } + } + + public class Foo + { + public Guid Id { get; } + public Foo MyFoo { get; set; } + + public Foo(Foo myFoo) + { + MyFoo = myFoo; + Id = Guid.NewGuid(); + } + } + + private JsonSerializerSettings DeserializeSettings(int maxDepth) => new JsonSerializerSettings() + { + TypeNameHandling = TypeNameHandling.None, + MaxDepth = maxDepth + }; + + private JsonSerializerSettings SerializeSettings(int maxDepth) => new JsonSerializerSettings() + { + TypeNameHandling = TypeNameHandling.All, + MaxDepth = maxDepth + }; + } +} +#endif diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index d43367cc3..72bc0cca2 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -1804,6 +1804,7 @@ private object CreateISerializable(JsonReader reader, JsonISerializableContract JsonConverter? itemConverter = GetConverter(itemContract, null, contract, member); JsonReader tokenReader = token.CreateReader(); + tokenReader.MaxDepth = Serializer.MaxDepth; tokenReader.ReadAndAssert(); // Move to first token object? result; From b13717a1c13b0747853568f11fc9e2aa0abf4649 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Mon, 14 Nov 2022 08:55:47 +0800 Subject: [PATCH 27/30] Add JsonCloneSettings to disable copy annotations (#2757) Co-authored-by: Sneha Shivakumar --- .../Linq/AnnotationsTests.cs | 129 ++++++++++++++++++ Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs | 2 +- .../MetadataPropertyHandlingTests.cs | 2 +- Src/Newtonsoft.Json/Linq/JArray.cs | 13 +- Src/Newtonsoft.Json/Linq/JConstructor.cs | 12 +- Src/Newtonsoft.Json/Linq/JContainer.cs | 46 ++++--- Src/Newtonsoft.Json/Linq/JObject.cs | 15 +- Src/Newtonsoft.Json/Linq/JProperty.cs | 18 ++- Src/Newtonsoft.Json/Linq/JRaw.cs | 11 +- Src/Newtonsoft.Json/Linq/JToken.cs | 18 ++- Src/Newtonsoft.Json/Linq/JTokenWriter.cs | 2 +- Src/Newtonsoft.Json/Linq/JValue.cs | 14 +- Src/Newtonsoft.Json/Linq/JsonCloneSettings.cs | 32 +++++ 13 files changed, 265 insertions(+), 49 deletions(-) create mode 100644 Src/Newtonsoft.Json/Linq/JsonCloneSettings.cs diff --git a/Src/Newtonsoft.Json.Tests/Linq/AnnotationsTests.cs b/Src/Newtonsoft.Json.Tests/Linq/AnnotationsTests.cs index 28af83764..7a8eb44ee 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/AnnotationsTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/AnnotationsTests.cs @@ -303,11 +303,140 @@ public void MultipleAnnotationsAreCopied() Assert.AreEqual(0, o2.Annotations().Count()); } + [Test] + public void NestedAnnotationsAreCopied() + { + Version version = new Version(1, 2, 3, 4); + + JObject o = new JObject(); + o.AddAnnotation("string!"); + o.AddAnnotation(version); + + JValue v = new JValue(true); + v.AddAnnotation("string!"); + v.AddAnnotation(version); + + o["Item1"] = v; + + JObject o2 = (JObject)o.DeepClone(); + Assert.AreEqual("string!", o2.Annotation()); + Assert.AreEqual(version, o2.Annotation()); + + JValue v2 = (JValue)o2["Item1"]; + Assert.AreEqual("string!", v2.Annotation()); + Assert.AreEqual(version, v2.Annotation()); + } + + [Test] + public void NestedAnnotationsAreCopiedWithDefault() + { + Version version = new Version(1, 2, 3, 4); + JsonCloneSettings settings = new JsonCloneSettings(); + + JObject o = new JObject(); + o.AddAnnotation("string!"); + o.AddAnnotation(version); + + JValue v = new JValue(true); + v.AddAnnotation("string!"); + v.AddAnnotation(version); + + o["Item1"] = v; + + JObject o2 = (JObject)o.DeepClone(settings); + Assert.AreEqual("string!", o2.Annotation()); + Assert.AreEqual(version, o2.Annotation()); + + JValue v2 = (JValue)o2["Item1"]; + Assert.AreEqual("string!", v2.Annotation()); + Assert.AreEqual(version, v2.Annotation()); + } + + [Test] + public void NestedAnnotationsAreNotCopiedWithSettingsCopyAnnotationsFalse() + { + Version version = new Version(1, 2, 3, 4); + JsonCloneSettings settings = new JsonCloneSettings() { CopyAnnotations = false }; + + JObject o = new JObject(); + o.AddAnnotation("string!"); + o.AddAnnotation(version); + + JValue v = new JValue(true); + v.AddAnnotation("string!"); + v.AddAnnotation(version); + + o["Item1"] = v; + + JObject o2 = (JObject)o.DeepClone(settings); + Assert.IsNull(o2.Annotation()); + Assert.AreEqual(0, o2.Annotations().Count()); + + JValue v2 = (JValue)o2["Item1"]; + Assert.IsNull(v2.Annotation()); + Assert.AreEqual(0, v2.Annotations().Count()); + } + private void AssertCloneCopy(JToken t, T annotation) where T : class { Assert.AreEqual(annotation, t.DeepClone().Annotation()); } + [Test] + public void MultipleAnnotationsAreNotCopiedWithSetting() + { + Version version = new Version(1, 2, 3, 4); + JsonCloneSettings settings = new JsonCloneSettings() { CopyAnnotations = false }; + + JObject o = new JObject(); + o.AddAnnotation("string!"); + o.AddAnnotation(version); + + JObject o2 = (JObject)o.DeepClone(settings); + Assert.IsNull(o2.Annotation()); + Assert.AreEqual(0, o2.Annotations().Count()); + + JArray a = new JArray(); + a.AddAnnotation("string!"); + a.AddAnnotation(version); + + JArray a2 = (JArray)a.DeepClone(settings); + Assert.IsNull(a2.Annotation()); + Assert.AreEqual(0, a2.Annotations().Count()); + + JProperty p = new JProperty("test"); + p.AddAnnotation("string!"); + p.AddAnnotation(version); + + JProperty p2 = (JProperty)p.DeepClone(settings); + Assert.IsNull(p2.Annotation()); + Assert.AreEqual(0, p2.Annotations().Count()); + + JRaw r = new JRaw("test"); + r.AddAnnotation("string!"); + r.AddAnnotation(version); + + JRaw r2 = (JRaw)r.DeepClone(settings); + Assert.IsNull(r2.Annotation()); + Assert.AreEqual(0, r2.Annotations().Count()); + + JConstructor c = new JConstructor("test"); + c.AddAnnotation("string!"); + c.AddAnnotation(version); + + JConstructor c2 = (JConstructor)c.DeepClone(settings); + Assert.IsNull(c2.Annotation()); + Assert.AreEqual(0, c2.Annotations().Count()); + + JValue v = new JValue("test"); + v.AddAnnotation("string!"); + v.AddAnnotation(version); + + JValue v2 = (JValue)v.DeepClone(settings); + Assert.IsNull(v2.Annotation()); + Assert.AreEqual(0, v2.Annotations().Count()); + } + #if !NET20 [Test] public void Example() diff --git a/Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs index cfeb102b3..57b7c3a88 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JRawTests.cs @@ -52,7 +52,7 @@ public void RawEquals() public void RawClone() { JRaw r1 = new JRaw("raw1"); - JToken r2 = r1.CloneToken(); + JToken r2 = r1.DeepClone(); CustomAssert.IsInstanceOfType(typeof(JRaw), r2); } diff --git a/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs index 2073dbcfe..e7d00dfb1 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/MetadataPropertyHandlingTests.cs @@ -324,7 +324,7 @@ public void DeserializeFromJToken() ]"; JToken t1 = JToken.Parse(json); - JToken t2 = t1.CloneToken(); + JToken t2 = t1.DeepClone(); List employees = t1.ToObject>(JsonSerializer.Create(new JsonSerializerSettings { diff --git a/Src/Newtonsoft.Json/Linq/JArray.cs b/Src/Newtonsoft.Json/Linq/JArray.cs index 241a56045..c589e211b 100644 --- a/Src/Newtonsoft.Json/Linq/JArray.cs +++ b/Src/Newtonsoft.Json/Linq/JArray.cs @@ -66,7 +66,12 @@ public JArray() /// /// A object to copy from. public JArray(JArray other) - : base(other) + : base(other, settings: null) + { + } + + internal JArray(JArray other, JsonCloneSettings? settings) + : base(other, settings) { } @@ -93,9 +98,9 @@ internal override bool DeepEquals(JToken node) return (node is JArray t && ContentsEqual(t)); } - internal override JToken CloneToken() + internal override JToken CloneToken(JsonCloneSettings? settings = null) { - return new JArray(this); + return new JArray(this, settings); } /// @@ -309,7 +314,7 @@ public int IndexOf(JToken item) /// public void Insert(int index, JToken item) { - InsertItem(index, item, false); + InsertItem(index, item, false, copyAnnotations: true); } /// diff --git a/Src/Newtonsoft.Json/Linq/JConstructor.cs b/Src/Newtonsoft.Json/Linq/JConstructor.cs index f2aa86182..703dbbc12 100644 --- a/Src/Newtonsoft.Json/Linq/JConstructor.cs +++ b/Src/Newtonsoft.Json/Linq/JConstructor.cs @@ -97,7 +97,13 @@ public JConstructor() /// /// A object to copy from. public JConstructor(JConstructor other) - : base(other) + : base(other, settings: null) + { + _name = other.Name; + } + + internal JConstructor(JConstructor other, JsonCloneSettings? settings) + : base(other, settings) { _name = other.Name; } @@ -147,9 +153,9 @@ internal override bool DeepEquals(JToken node) return (node is JConstructor c && _name == c.Name && ContentsEqual(c)); } - internal override JToken CloneToken() + internal override JToken CloneToken(JsonCloneSettings? settings = null) { - return new JConstructor(this); + return new JConstructor(this, settings); } /// diff --git a/Src/Newtonsoft.Json/Linq/JContainer.cs b/Src/Newtonsoft.Json/Linq/JContainer.cs index f9447cd5d..e19be3619 100644 --- a/Src/Newtonsoft.Json/Linq/JContainer.cs +++ b/Src/Newtonsoft.Json/Linq/JContainer.cs @@ -106,19 +106,24 @@ internal JContainer() { } - internal JContainer(JContainer other) + internal JContainer(JContainer other, JsonCloneSettings? settings) : this() { ValidationUtils.ArgumentNotNull(other, nameof(other)); + bool copyAnnotations = settings?.CopyAnnotations ?? true; + + if (copyAnnotations) + { + CopyAnnotations(this, other); + } + int i = 0; foreach (JToken child in other) { - TryAddInternal(i, child, false); + TryAddInternal(i, child, false, copyAnnotations); i++; } - - CopyAnnotations(this, other); } internal void CheckReentrancy() @@ -323,7 +328,7 @@ internal bool IsMultiContent([NotNullWhen(true)]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, bool copyAnnotations) { if (item == null) { @@ -341,7 +346,12 @@ internal JToken EnsureParentToken(JToken? item, bool skipParentCheck) // the item is being added to the root parent of itself if (item.Parent != null || item == this || (item.HasValues && Root == item)) { - item = item.CloneToken(); + // Avoid allocating settings when copy annotations is false. + JsonCloneSettings? settings = copyAnnotations + ? null + : JsonCloneSettings.SkipCopyAnnotations; + + item = item.CloneToken(settings); } return item; @@ -349,7 +359,7 @@ internal JToken EnsureParentToken(JToken? item, bool skipParentCheck) internal abstract int IndexOfItem(JToken? item); - internal virtual bool InsertItem(int index, JToken? item, bool skipParentCheck) + internal virtual bool InsertItem(int index, JToken? item, bool skipParentCheck, bool copyAnnotations) { IList children = ChildrenTokens; @@ -360,7 +370,7 @@ internal virtual bool InsertItem(int index, JToken? item, bool skipParentCheck) CheckReentrancy(); - item = EnsureParentToken(item, skipParentCheck); + item = EnsureParentToken(item, skipParentCheck, copyAnnotations); JToken? previous = (index == 0) ? null : children[index - 1]; // haven't inserted new token yet so next token is still at the inserting index @@ -490,7 +500,7 @@ internal virtual void SetItem(int index, JToken? item) CheckReentrancy(); - item = EnsureParentToken(item, false); + item = EnsureParentToken(item, false, copyAnnotations: true); ValidateToken(item, existing); @@ -635,17 +645,17 @@ internal virtual void ValidateToken(JToken o, JToken? existing) /// The content to be added. public virtual void Add(object? content) { - TryAddInternal(ChildrenTokens.Count, content, false); + TryAddInternal(ChildrenTokens.Count, content, false, copyAnnotations: true); } internal bool TryAdd(object? content) { - return TryAddInternal(ChildrenTokens.Count, content, false); + return TryAddInternal(ChildrenTokens.Count, content, false, copyAnnotations: true); } internal void AddAndSkipParentCheck(JToken token) { - TryAddInternal(ChildrenTokens.Count, token, true); + TryAddInternal(ChildrenTokens.Count, token, true, copyAnnotations: true); } /// @@ -654,10 +664,10 @@ internal void AddAndSkipParentCheck(JToken token) /// The content to be added. public void AddFirst(object? content) { - TryAddInternal(0, content, false); + TryAddInternal(0, content, false, copyAnnotations: true); } - internal bool TryAddInternal(int index, object? content, bool skipParentCheck) + internal bool TryAddInternal(int index, object? content, bool skipParentCheck, bool copyAnnotations) { if (IsMultiContent(content)) { @@ -666,7 +676,7 @@ internal bool TryAddInternal(int index, object? content, bool skipParentCheck) int multiIndex = index; foreach (object c in enumerable) { - TryAddInternal(multiIndex, c, skipParentCheck); + TryAddInternal(multiIndex, c, skipParentCheck, copyAnnotations); multiIndex++; } @@ -676,7 +686,7 @@ internal bool TryAddInternal(int index, object? content, bool skipParentCheck) { JToken item = CreateFromContent(content); - return InsertItem(index, item, skipParentCheck); + return InsertItem(index, item, skipParentCheck, copyAnnotations); } } @@ -963,7 +973,7 @@ int IList.IndexOf(JToken item) void IList.Insert(int index, JToken item) { - InsertItem(index, item, false); + InsertItem(index, item, false, copyAnnotations: true); } void IList.RemoveAt(int index) @@ -1046,7 +1056,7 @@ int IList.IndexOf(object? value) void IList.Insert(int index, object? value) { - InsertItem(index, EnsureValue(value), false); + InsertItem(index, EnsureValue(value), false, copyAnnotations: false); } bool IList.IsFixedSize => false; diff --git a/Src/Newtonsoft.Json/Linq/JObject.cs b/Src/Newtonsoft.Json/Linq/JObject.cs index 872c8ae7c..fab460da4 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.cs @@ -93,7 +93,12 @@ public JObject() /// /// A object to copy from. public JObject(JObject other) - : base(other) + : base(other, settings: null) + { + } + + internal JObject(JObject other, JsonCloneSettings? settings) + : base(other, settings) { } @@ -135,7 +140,7 @@ internal override int IndexOfItem(JToken? item) return _properties.IndexOfReference(item); } - internal override bool InsertItem(int index, JToken? item, bool skipParentCheck) + internal override bool InsertItem(int index, JToken? item, bool skipParentCheck, bool copyAnnotations) { // don't add comments to JObject, no name to reference comment by if (item != null && item.Type == JTokenType.Comment) @@ -143,7 +148,7 @@ internal override bool InsertItem(int index, JToken? item, bool skipParentCheck) return false; } - return base.InsertItem(index, item, skipParentCheck); + return base.InsertItem(index, item, skipParentCheck, copyAnnotations); } internal override void ValidateToken(JToken o, JToken? existing) @@ -244,9 +249,9 @@ internal void InternalPropertyChanging(JProperty childProperty) #endif } - internal override JToken CloneToken() + internal override JToken CloneToken(JsonCloneSettings? settings) { - return new JObject(this); + return new JObject(this, settings); } /// diff --git a/Src/Newtonsoft.Json/Linq/JProperty.cs b/Src/Newtonsoft.Json/Linq/JProperty.cs index 3c738cf52..b8c7ace6a 100644 --- a/Src/Newtonsoft.Json/Linq/JProperty.cs +++ b/Src/Newtonsoft.Json/Linq/JProperty.cs @@ -173,7 +173,7 @@ public JToken Value if (_content._token == null) { - InsertItem(0, newValue, false); + InsertItem(0, newValue, false, copyAnnotations: true); } else { @@ -187,7 +187,13 @@ public JToken Value /// /// A object to copy from. public JProperty(JProperty other) - : base(other) + : base(other, settings: null) + { + _name = other.Name; + } + + internal JProperty(JProperty other, JsonCloneSettings? settings) + : base(other, settings) { _name = other.Name; } @@ -241,7 +247,7 @@ internal override int IndexOfItem(JToken? item) return _content.IndexOf(item); } - internal override bool InsertItem(int index, JToken? item, bool skipParentCheck) + internal override bool InsertItem(int index, JToken? item, bool skipParentCheck, bool copyAnnotations) { // don't add comments to JProperty if (item != null && item.Type == JTokenType.Comment) @@ -254,7 +260,7 @@ internal override bool InsertItem(int index, JToken? item, bool skipParentCheck) throw new JsonException("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } - return base.InsertItem(0, item, false); + return base.InsertItem(0, item, false, copyAnnotations); } internal override bool ContainsItem(JToken? item) @@ -282,9 +288,9 @@ internal override bool DeepEquals(JToken node) return (node is JProperty t && _name == t.Name && ContentsEqual(t)); } - internal override JToken CloneToken() + internal override JToken CloneToken(JsonCloneSettings? settings) { - return new JProperty(this); + return new JProperty(this, settings); } /// diff --git a/Src/Newtonsoft.Json/Linq/JRaw.cs b/Src/Newtonsoft.Json/Linq/JRaw.cs index 02ca51fd1..02ca96d3c 100644 --- a/Src/Newtonsoft.Json/Linq/JRaw.cs +++ b/Src/Newtonsoft.Json/Linq/JRaw.cs @@ -38,7 +38,12 @@ public partial class JRaw : JValue /// /// A object to copy from. public JRaw(JRaw other) - : base(other) + : base(other, settings: null) + { + } + + internal JRaw(JRaw other, JsonCloneSettings? settings) + : base(other, settings) { } @@ -67,9 +72,9 @@ public static JRaw Create(JsonReader reader) } } - internal override JToken CloneToken() + internal override JToken CloneToken(JsonCloneSettings? settings) { - return new JRaw(this); + return new JRaw(this, settings); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 336d748aa..27f84d8ba 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -131,7 +131,7 @@ public JToken Root } } - internal abstract JToken CloneToken(); + internal abstract JToken CloneToken(JsonCloneSettings? settings); internal abstract bool DeepEquals(JToken node); /// @@ -241,7 +241,7 @@ public void AddAfterSelf(object? content) } int index = _parent.IndexOfItem(this); - _parent.TryAddInternal(index + 1, content, false); + _parent.TryAddInternal(index + 1, content, false, copyAnnotations: true); } /// @@ -256,7 +256,7 @@ public void AddBeforeSelf(object? content) } int index = _parent.IndexOfItem(this); - _parent.TryAddInternal(index, content, false); + _parent.TryAddInternal(index, content, false, copyAnnotations: true); } /// @@ -2443,7 +2443,17 @@ object ICloneable.Clone() /// A new instance of the . public JToken DeepClone() { - return CloneToken(); + return CloneToken(settings: null); + } + + /// + /// Creates a new instance of the . All child tokens are recursively cloned. + /// + /// A object to configure cloning settings. + /// A new instance of the . + public JToken DeepClone(JsonCloneSettings settings) + { + return CloneToken(settings); } /// diff --git a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs index 344ae8343..618063e24 100644 --- a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs +++ b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs @@ -502,7 +502,7 @@ internal override void WriteToken(JsonReader reader, bool writeChildren, bool wr } } - JToken value = tokenReader.CurrentToken!.CloneToken(); + JToken value = tokenReader.CurrentToken!.CloneToken(settings: null); if (_parent != null) { diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs index 09ed1fd42..c2f03991c 100644 --- a/Src/Newtonsoft.Json/Linq/JValue.cs +++ b/Src/Newtonsoft.Json/Linq/JValue.cs @@ -57,6 +57,15 @@ internal JValue(object? value, JTokenType type) _valueType = type; } + internal JValue(JValue other, JsonCloneSettings? settings) + : this(other.Value, other.Type) + { + if (settings?.CopyAnnotations ?? true) + { + CopyAnnotations(this, other); + } + } + /// /// Initializes a new instance of the class from another object. /// @@ -64,7 +73,6 @@ internal JValue(object? value, JTokenType type) public JValue(JValue other) : this(other.Value, other.Type) { - CopyAnnotations(this, other); } /// @@ -557,9 +565,9 @@ private static bool Operation(ExpressionType operation, object? objA, object? ob } #endif - internal override JToken CloneToken() + internal override JToken CloneToken(JsonCloneSettings? settings) { - return new JValue(this); + return new JValue(this, settings); } /// diff --git a/Src/Newtonsoft.Json/Linq/JsonCloneSettings.cs b/Src/Newtonsoft.Json/Linq/JsonCloneSettings.cs new file mode 100644 index 000000000..02f1351cc --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JsonCloneSettings.cs @@ -0,0 +1,32 @@ +using System; + +namespace Newtonsoft.Json.Linq +{ + /// + /// Specifies the settings used when cloning JSON. + /// + public class JsonCloneSettings + { + internal static readonly JsonCloneSettings SkipCopyAnnotations = new JsonCloneSettings + { + CopyAnnotations = false + }; + + /// + /// Initializes a new instance of the class. + /// + public JsonCloneSettings() + { + CopyAnnotations = true; + } + + /// + /// Gets or sets a flag that indicates whether to copy annotations when cloning a . + /// The default value is true. + /// + /// + /// A flag that indicates whether to copy annotations when cloning a . + /// + public bool CopyAnnotations { get; set; } + } +} \ No newline at end of file From 789bfd3bbcd3d5e567bcfb57a1d08fb8611adf96 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Mon, 14 Nov 2022 09:09:19 +0800 Subject: [PATCH 28/30] Update to 13.0.2-beta3 --- Build/version.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Build/version.json b/Build/version.json index 69db9f005..4f6b30181 100644 --- a/Build/version.json +++ b/Build/version.json @@ -1,6 +1,6 @@ { "Major": 13, "Release": 2, - "Prerelease": "beta2", + "Prerelease": "beta3", "Assembly": null } \ No newline at end of file From b15df4b50de66065711d5d613f2531e372297fcf Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Thu, 24 Nov 2022 09:56:09 +0800 Subject: [PATCH 29/30] Add missing headers --- Src/Newtonsoft.Json/Linq/JsonCloneSettings.cs | 25 +++++++++++++++++ Src/Newtonsoft.Json/Linq/JsonLoadSettings.cs | 27 ++++++++++++++++++- .../Linq/JsonSelectSettings.cs | 27 ++++++++++++++++++- .../Linq/MergeArrayHandling.cs | 25 +++++++++++++++++ .../Linq/MergeNullValueHandling.cs | 27 ++++++++++++++++++- 5 files changed, 128 insertions(+), 3 deletions(-) diff --git a/Src/Newtonsoft.Json/Linq/JsonCloneSettings.cs b/Src/Newtonsoft.Json/Linq/JsonCloneSettings.cs index 02f1351cc..bad671e43 100644 --- a/Src/Newtonsoft.Json/Linq/JsonCloneSettings.cs +++ b/Src/Newtonsoft.Json/Linq/JsonCloneSettings.cs @@ -1,3 +1,28 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + using System; namespace Newtonsoft.Json.Linq diff --git a/Src/Newtonsoft.Json/Linq/JsonLoadSettings.cs b/Src/Newtonsoft.Json/Linq/JsonLoadSettings.cs index 64aba4c10..2c224ac2d 100644 --- a/Src/Newtonsoft.Json/Linq/JsonLoadSettings.cs +++ b/Src/Newtonsoft.Json/Linq/JsonLoadSettings.cs @@ -1,4 +1,29 @@ -using System; +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; namespace Newtonsoft.Json.Linq { diff --git a/Src/Newtonsoft.Json/Linq/JsonSelectSettings.cs b/Src/Newtonsoft.Json/Linq/JsonSelectSettings.cs index 495b2dc01..860ec455a 100644 --- a/Src/Newtonsoft.Json/Linq/JsonSelectSettings.cs +++ b/Src/Newtonsoft.Json/Linq/JsonSelectSettings.cs @@ -1,4 +1,29 @@ -using System; +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; namespace Newtonsoft.Json.Linq { diff --git a/Src/Newtonsoft.Json/Linq/MergeArrayHandling.cs b/Src/Newtonsoft.Json/Linq/MergeArrayHandling.cs index 5e7fadf12..c4cd8d72b 100644 --- a/Src/Newtonsoft.Json/Linq/MergeArrayHandling.cs +++ b/Src/Newtonsoft.Json/Linq/MergeArrayHandling.cs @@ -1,3 +1,28 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + namespace Newtonsoft.Json.Linq { /// diff --git a/Src/Newtonsoft.Json/Linq/MergeNullValueHandling.cs b/Src/Newtonsoft.Json/Linq/MergeNullValueHandling.cs index 30d3d845d..1e41585b1 100644 --- a/Src/Newtonsoft.Json/Linq/MergeNullValueHandling.cs +++ b/Src/Newtonsoft.Json/Linq/MergeNullValueHandling.cs @@ -1,4 +1,29 @@ -using System; +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; namespace Newtonsoft.Json.Linq { From 4fba53a324c445f06ee08e45a015c346000a7ef2 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Thu, 24 Nov 2022 10:02:04 +0800 Subject: [PATCH 30/30] Remove prerelease for 13.0.2 --- Build/version.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Build/version.json b/Build/version.json index 4f6b30181..7e0f6ad33 100644 --- a/Build/version.json +++ b/Build/version.json @@ -1,6 +1,6 @@ { "Major": 13, "Release": 2, - "Prerelease": "beta3", + "Prerelease": null, "Assembly": null } \ No newline at end of file