From c9b2ec8055fef3e2ff7be3ae6dd9850e57a43473 Mon Sep 17 00:00:00 2001 From: Jon Hanna Date: Fri, 6 Jan 2017 13:27:11 +0000 Subject: [PATCH] Async JToken methods --- .../Linq/JConstructorAsyncTests.cs | 58 ++ .../Linq/JObjectAsyncTests.cs | 168 ++++ .../Linq/JPropertyAsyncTests.cs | 74 ++ .../Linq/JTokenAsyncTests.cs | 124 +++ .../Linq/JTokenReaderAsyncTests.cs | 881 ++++++++++++++++++ .../Linq/JTokenWriterAsyncTests.cs | 391 ++++++++ .../Linq/JValueAsyncTests.cs | 111 +++ .../Linq/LinqToJsonAsyncTests.cs | 174 ++++ .../Newtonsoft.Json.Tests.Portable.csproj | 8 + .../Newtonsoft.Json.Tests.csproj | 8 + Src/Newtonsoft.Json/JsonReader.Async.cs | 25 + Src/Newtonsoft.Json/JsonTextWriter.Async.cs | 2 +- Src/Newtonsoft.Json/JsonWriter.Async.cs | 25 +- Src/Newtonsoft.Json/Linq/JArray.Async.cs | 103 ++ Src/Newtonsoft.Json/Linq/JArray.cs | 2 +- .../Linq/JConstructor.Async.cs | 106 +++ Src/Newtonsoft.Json/Linq/JConstructor.cs | 7 +- Src/Newtonsoft.Json/Linq/JContainer.Async.cs | 175 ++++ Src/Newtonsoft.Json/Linq/JContainer.cs | 2 +- Src/Newtonsoft.Json/Linq/JObject.Async.cs | 108 +++ Src/Newtonsoft.Json/Linq/JObject.cs | 2 +- Src/Newtonsoft.Json/Linq/JProperty.Async.cs | 107 +++ Src/Newtonsoft.Json/Linq/JProperty.cs | 2 +- Src/Newtonsoft.Json/Linq/JRaw.Async.cs | 57 ++ Src/Newtonsoft.Json/Linq/JRaw.cs | 2 +- Src/Newtonsoft.Json/Linq/JToken.Async.cs | 178 ++++ Src/Newtonsoft.Json/Linq/JToken.cs | 2 +- .../Linq/JTokenWriter.Async.cs | 53 ++ Src/Newtonsoft.Json/Linq/JTokenWriter.cs | 2 +- Src/Newtonsoft.Json/Linq/JValue.Async.cs | 138 +++ Src/Newtonsoft.Json/Linq/JValue.cs | 2 +- .../Newtonsoft.Json.Portable.csproj | 9 + Src/Newtonsoft.Json/Newtonsoft.Json.csproj | 9 + 33 files changed, 3102 insertions(+), 13 deletions(-) create mode 100644 Src/Newtonsoft.Json.Tests/Linq/JConstructorAsyncTests.cs create mode 100644 Src/Newtonsoft.Json.Tests/Linq/JObjectAsyncTests.cs create mode 100644 Src/Newtonsoft.Json.Tests/Linq/JPropertyAsyncTests.cs create mode 100644 Src/Newtonsoft.Json.Tests/Linq/JTokenAsyncTests.cs create mode 100644 Src/Newtonsoft.Json.Tests/Linq/JTokenReaderAsyncTests.cs create mode 100644 Src/Newtonsoft.Json.Tests/Linq/JTokenWriterAsyncTests.cs create mode 100644 Src/Newtonsoft.Json.Tests/Linq/JValueAsyncTests.cs create mode 100644 Src/Newtonsoft.Json.Tests/Linq/LinqToJsonAsyncTests.cs create mode 100644 Src/Newtonsoft.Json/Linq/JArray.Async.cs create mode 100644 Src/Newtonsoft.Json/Linq/JConstructor.Async.cs create mode 100644 Src/Newtonsoft.Json/Linq/JContainer.Async.cs create mode 100644 Src/Newtonsoft.Json/Linq/JObject.Async.cs create mode 100644 Src/Newtonsoft.Json/Linq/JProperty.Async.cs create mode 100644 Src/Newtonsoft.Json/Linq/JRaw.Async.cs create mode 100644 Src/Newtonsoft.Json/Linq/JToken.Async.cs create mode 100644 Src/Newtonsoft.Json/Linq/JTokenWriter.Async.cs create mode 100644 Src/Newtonsoft.Json/Linq/JValue.Async.cs diff --git a/Src/Newtonsoft.Json.Tests/Linq/JConstructorAsyncTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JConstructorAsyncTests.cs new file mode 100644 index 00000000..3ed7a9c5 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Linq/JConstructorAsyncTests.cs @@ -0,0 +1,58 @@ +#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 || PORTABLE40) + +using Newtonsoft.Json.Linq; +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace Newtonsoft.Json.Tests.Linq +{ + [TestFixture] + public class JConstructorAsyncTests : TestFixtureBase + { + [Test] + public async Task LoadAsync() + { + JsonReader reader = new JsonTextReader(new StringReader("new Date(123)")); + await reader.ReadAsync(); + + JConstructor constructor = await JConstructor.LoadAsync(reader); + Assert.AreEqual("Date", constructor.Name); + Assert.IsTrue(JToken.DeepEquals(new JValue(123), constructor.Values().ElementAt(0))); + } + } +} + +#endif diff --git a/Src/Newtonsoft.Json.Tests/Linq/JObjectAsyncTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JObjectAsyncTests.cs new file mode 100644 index 00000000..4a440088 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Linq/JObjectAsyncTests.cs @@ -0,0 +1,168 @@ +#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 || PORTABLE40) + +using System.Collections.Generic; +using Newtonsoft.Json.Tests.TestObjects; +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif +using Newtonsoft.Json.Linq; +using System.IO; +using System.Threading.Tasks; + +namespace Newtonsoft.Json.Tests.Linq +{ + [TestFixture] + public class JObjectAsyncTests : TestFixtureBase + { + [Test] + public async Task ReadWithSupportMultipleContentAsync() + { + string json = @"{ 'name': 'Admin' }{ 'name': 'Publisher' }"; + + IList roles = new List(); + + JsonTextReader reader = new JsonTextReader(new StringReader(json)); + reader.SupportMultipleContent = true; + + while (true) + { + JObject role = (JObject)await JToken.ReadFromAsync(reader); + + roles.Add(role); + + if (!await reader.ReadAsync()) + { + break; + } + } + + Assert.AreEqual(2, roles.Count); + Assert.AreEqual("Admin", (string)roles[0]["name"]); + Assert.AreEqual("Publisher", (string)roles[1]["name"]); + } + + [Test] + public async Task JTokenReaderAsync() + { + PersonRaw raw = new PersonRaw + { + FirstName = "FirstNameValue", + RawContent = new JRaw("[1,2,3,4,5]"), + LastName = "LastNameValue" + }; + + JObject o = JObject.FromObject(raw); + + JsonReader reader = new JTokenReader(o); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.String, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.Raw, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.String, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.EndObject, reader.TokenType); + + Assert.IsFalse(await reader.ReadAsync()); + } + + [Test] + public async Task LoadFromNestedObjectAsync() + { + string jsonText = @"{ + ""short"": + { + ""error"": + { + ""code"":0, + ""msg"":""No action taken"" + } + } +}"; + + JsonReader reader = new JsonTextReader(new StringReader(jsonText)); + await reader.ReadAsync(); + await reader.ReadAsync(); + await reader.ReadAsync(); + await reader.ReadAsync(); + await reader.ReadAsync(); + + JObject o = (JObject)await JToken.ReadFromAsync(reader); + Assert.IsNotNull(o); + StringAssert.AreEqual(@"{ + ""code"": 0, + ""msg"": ""No action taken"" +}", o.ToString(Formatting.Indented)); + } + + [Test] + public async Task LoadFromNestedObjectIncompleteAsync() + { + await ExceptionAssert.ThrowsAsync(async () => + { + string jsonText = @"{ + ""short"": + { + ""error"": + { + ""code"":0"; + + JsonReader reader = new JsonTextReader(new StringReader(jsonText)); + await reader.ReadAsync(); + await reader.ReadAsync(); + await reader.ReadAsync(); + await reader.ReadAsync(); + await reader.ReadAsync(); + + await JToken.ReadFromAsync(reader); + }, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 14."); + } + } +} + +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/JPropertyAsyncTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JPropertyAsyncTests.cs new file mode 100644 index 00000000..15a12ab5 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Linq/JPropertyAsyncTests.cs @@ -0,0 +1,74 @@ +#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 || PORTABLE40) + +using Newtonsoft.Json.Linq; +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif +using System.IO; +using System.Threading.Tasks; + +namespace Newtonsoft.Json.Tests.Linq +{ + [TestFixture] + public class JPropertyAsyncTests : TestFixtureBase + { + [Test] + public async Task LoadAsync() + { + JsonReader reader = new JsonTextReader(new StringReader("{'propertyname':['value1']}")); + await reader.ReadAsync(); + + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + await reader.ReadAsync(); + + JProperty property = await JProperty.LoadAsync(reader); + Assert.AreEqual("propertyname", property.Name); + Assert.IsTrue(JToken.DeepEquals(JArray.Parse("['value1']"), property.Value)); + + Assert.AreEqual(JsonToken.EndObject, reader.TokenType); + + reader = new JsonTextReader(new StringReader("{'propertyname':null}")); + await reader.ReadAsync(); + + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + await reader.ReadAsync(); + + property = await JProperty.LoadAsync(reader); + Assert.AreEqual("propertyname", property.Name); + Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), property.Value)); + + Assert.AreEqual(JsonToken.EndObject, reader.TokenType); + } + } +} + +#endif diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenAsyncTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenAsyncTests.cs new file mode 100644 index 00000000..b8a3b8cc --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenAsyncTests.cs @@ -0,0 +1,124 @@ +#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 || PORTABLE40) + +using System; +using System.Threading.Tasks; +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif +using Newtonsoft.Json.Linq; +using System.IO; +using System.Linq; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Tests.Linq +{ + [TestFixture] + public class JTokenAsyncTests : TestFixtureBase + { + [Test] + public async Task ReadFromAsync() + { + JObject o = (JObject)await JToken.ReadFromAsync(new JsonTextReader(new StringReader("{'pie':true}"))); + Assert.AreEqual(true, (bool)o["pie"]); + + JArray a = (JArray)await JToken.ReadFromAsync(new JsonTextReader(new StringReader("[1,2,3]"))); + Assert.AreEqual(1, (int)a[0]); + Assert.AreEqual(2, (int)a[1]); + Assert.AreEqual(3, (int)a[2]); + + JsonReader reader = new JsonTextReader(new StringReader("{'pie':true}")); + await reader.ReadAsync(); + await reader.ReadAsync(); + + JProperty p = (JProperty)await JToken.ReadFromAsync(reader); + Assert.AreEqual("pie", p.Name); + Assert.AreEqual(true, (bool)p.Value); + + JConstructor c = (JConstructor)await JToken.ReadFromAsync(new JsonTextReader(new StringReader("new Date(1)"))); + Assert.AreEqual("Date", c.Name); + Assert.IsTrue(JToken.DeepEquals(new JValue(1), c.Values().ElementAt(0))); + + JValue v = (JValue)await JToken.ReadFromAsync(new JsonTextReader(new StringReader(@"""stringvalue"""))); + Assert.AreEqual("stringvalue", (string)v); + + v = (JValue)await JToken.ReadFromAsync(new JsonTextReader(new StringReader(@"1"))); + Assert.AreEqual(1, (int)v); + + v = (JValue)await JToken.ReadFromAsync(new JsonTextReader(new StringReader(@"1.1"))); + Assert.AreEqual(1.1, (double)v); + + v = (JValue)await JToken.ReadFromAsync(new JsonTextReader(new StringReader(@"""1970-01-01T00:00:00+12:31""")) + { + DateParseHandling = DateParseHandling.DateTimeOffset + }); + Assert.AreEqual(typeof(DateTimeOffset), v.Value.GetType()); + Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, new TimeSpan(12, 31, 0)), v.Value); + } + + [Test] + public async Task LoadAsync() + { + JObject o = (JObject)await JToken.LoadAsync(new JsonTextReader(new StringReader("{'pie':true}"))); + Assert.AreEqual(true, (bool)o["pie"]); + } + + [Test] + public async Task CreateWriterAsync() + { + JArray a = + new JArray( + 5, + new JArray(1), + new JArray(1, 2), + new JArray(1, 2, 3) + ); + + JsonWriter writer = a.CreateWriter(); + Assert.IsNotNull(writer); + Assert.AreEqual(4, a.Count); + + await writer.WriteValueAsync("String"); + Assert.AreEqual(5, a.Count); + Assert.AreEqual("String", (string)a[4]); + + await writer.WriteStartObjectAsync(); + await writer.WritePropertyNameAsync("Property"); + await writer.WriteValueAsync("PropertyValue"); + await writer.WriteEndAsync(); + + Assert.AreEqual(6, a.Count); + Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("Property", "PropertyValue")), a[5])); + } + } +} + +#endif diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderAsyncTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderAsyncTests.cs new file mode 100644 index 00000000..e43dcb13 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderAsyncTests.cs @@ -0,0 +1,881 @@ +#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 || PORTABLE40) + +using System; +using System.Text; +using System.Threading.Tasks; +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif +using System.IO; +#if !PORTABLE || NETSTANDARD1_1 +using System.Numerics; +#endif +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Tests.Serialization; +using Newtonsoft.Json.Tests.TestObjects; + +namespace Newtonsoft.Json.Tests.Linq +{ + [TestFixture] + public class JTokenReaderAsyncTests : TestFixtureBase + { +#if !PORTABLE || NETSTANDARD1_1 + [Test] + public async Task ConvertBigIntegerToDoubleAsync() + { + var jObject = JObject.Parse("{ maxValue:10000000000000000000}"); + + JsonReader reader = jObject.CreateReader(); + Assert.IsTrue(await reader.ReadAsync()); + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(10000000000000000000d, await reader.ReadAsDoubleAsync()); + Assert.IsTrue(await reader.ReadAsync()); + } +#endif + + [Test] + public async Task YahooFinanceAsync() + { + JObject o = + new JObject( + new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)), + new JProperty("Test2", new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0))), + new JProperty("Test3", "Test3Value"), + new JProperty("Test4", null) + ); + + using (JTokenReader jsonReader = new JTokenReader(o)) + { + IJsonLineInfo lineInfo = jsonReader; + + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); + Assert.AreEqual(false, lineInfo.HasLineInfo()); + + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); + Assert.AreEqual("Test1", jsonReader.Value); + Assert.AreEqual(false, lineInfo.HasLineInfo()); + + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); + Assert.AreEqual(new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc), jsonReader.Value); + Assert.AreEqual(false, lineInfo.HasLineInfo()); + Assert.AreEqual(0, lineInfo.LinePosition); + Assert.AreEqual(0, lineInfo.LineNumber); + + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); + Assert.AreEqual("Test2", jsonReader.Value); + + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); + Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value); + + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); + Assert.AreEqual("Test3", jsonReader.Value); + + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.String, jsonReader.TokenType); + Assert.AreEqual("Test3Value", jsonReader.Value); + + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); + Assert.AreEqual("Test4", jsonReader.Value); + + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.Null, jsonReader.TokenType); + Assert.AreEqual(null, jsonReader.Value); + + Assert.IsTrue(await jsonReader.ReadAsync()); + Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType); + + Assert.IsFalse(await jsonReader.ReadAsync()); + Assert.AreEqual(JsonToken.None, jsonReader.TokenType); + } + + using (JsonReader jsonReader = new JTokenReader(o.Property("Test2"))) + { + Assert.IsTrue(await jsonReader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); + Assert.AreEqual("Test2", jsonReader.Value); + + Assert.IsTrue(await jsonReader.ReadAsync()); + Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); + Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value); + + Assert.IsFalse(await jsonReader.ReadAsync()); + Assert.AreEqual(JsonToken.None, jsonReader.TokenType); + } + } + + [Test] + public async Task ReadAsDateTimeOffsetBadStringAsync() + { + string json = @"{""Offset"":""blablahbla""}"; + + JObject o = JObject.Parse(json); + + JsonReader reader = o.CreateReader(); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + await ExceptionAssert.ThrowsAsync(async () => { await reader.ReadAsDateTimeOffsetAsync(); }, "Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22."); + } + + [Test] + public async Task ReadAsDateTimeOffsetBooleanAsync() + { + string json = @"{""Offset"":true}"; + + JObject o = JObject.Parse(json); + + JsonReader reader = o.CreateReader(); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + await ExceptionAssert.ThrowsAsync(async () => { await reader.ReadAsDateTimeOffsetAsync(); }, "Error reading date. Unexpected token: Boolean. Path 'Offset', line 1, position 14."); + } + + [Test] + public async Task ReadAsDateTimeOffsetStringAsync() + { + string json = @"{""Offset"":""2012-01-24T03:50Z""}"; + + JObject o = JObject.Parse(json); + + JsonReader reader = o.CreateReader(); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + await reader.ReadAsDateTimeOffsetAsync(); + Assert.AreEqual(JsonToken.Date, reader.TokenType); + Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType); + Assert.AreEqual(new DateTimeOffset(2012, 1, 24, 3, 50, 0, TimeSpan.Zero), reader.Value); + } + + [Test] + public async Task ReadLineInfoAsync() + { + string input = @"{ + CPU: 'Intel', + Drives: [ + 'DVD read/writer', + ""500 gigabyte hard drive"" + ] +}"; + + JObject o = JObject.Parse(input); + + using (JTokenReader jsonReader = new JTokenReader(o)) + { + IJsonLineInfo lineInfo = jsonReader; + + Assert.AreEqual(jsonReader.TokenType, JsonToken.None); + Assert.AreEqual(0, lineInfo.LineNumber); + Assert.AreEqual(0, lineInfo.LinePosition); + Assert.AreEqual(false, lineInfo.HasLineInfo()); + Assert.AreEqual(null, jsonReader.CurrentToken); + + await jsonReader.ReadAsync(); + Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject); + Assert.AreEqual(1, lineInfo.LineNumber); + Assert.AreEqual(1, lineInfo.LinePosition); + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(o, jsonReader.CurrentToken); + + await jsonReader.ReadAsync(); + Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); + Assert.AreEqual(jsonReader.Value, "CPU"); + Assert.AreEqual(2, lineInfo.LineNumber); + Assert.AreEqual(6, lineInfo.LinePosition); + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(o.Property("CPU"), jsonReader.CurrentToken); + + await jsonReader.ReadAsync(); + Assert.AreEqual(jsonReader.TokenType, JsonToken.String); + Assert.AreEqual(jsonReader.Value, "Intel"); + Assert.AreEqual(2, lineInfo.LineNumber); + Assert.AreEqual(14, lineInfo.LinePosition); + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(o.Property("CPU").Value, jsonReader.CurrentToken); + + await jsonReader.ReadAsync(); + Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); + Assert.AreEqual(jsonReader.Value, "Drives"); + Assert.AreEqual(3, lineInfo.LineNumber); + Assert.AreEqual(9, lineInfo.LinePosition); + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(o.Property("Drives"), jsonReader.CurrentToken); + + await jsonReader.ReadAsync(); + Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray); + Assert.AreEqual(3, lineInfo.LineNumber); + Assert.AreEqual(11, lineInfo.LinePosition); + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(o.Property("Drives").Value, jsonReader.CurrentToken); + + await jsonReader.ReadAsync(); + Assert.AreEqual(jsonReader.TokenType, JsonToken.String); + Assert.AreEqual(jsonReader.Value, "DVD read/writer"); + Assert.AreEqual(4, lineInfo.LineNumber); + Assert.AreEqual(21, lineInfo.LinePosition); + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(o["Drives"][0], jsonReader.CurrentToken); + + await jsonReader.ReadAsync(); + Assert.AreEqual(jsonReader.TokenType, JsonToken.String); + Assert.AreEqual(jsonReader.Value, "500 gigabyte hard drive"); + Assert.AreEqual(5, lineInfo.LineNumber); + Assert.AreEqual(29, lineInfo.LinePosition); + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(o["Drives"][1], jsonReader.CurrentToken); + + await jsonReader.ReadAsync(); + Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray); + Assert.AreEqual(3, lineInfo.LineNumber); + Assert.AreEqual(11, lineInfo.LinePosition); + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(o["Drives"], jsonReader.CurrentToken); + + await jsonReader.ReadAsync(); + Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject); + Assert.AreEqual(1, lineInfo.LineNumber); + Assert.AreEqual(1, lineInfo.LinePosition); + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(o, jsonReader.CurrentToken); + + await jsonReader.ReadAsync(); + Assert.AreEqual(jsonReader.TokenType, JsonToken.None); + Assert.AreEqual(null, jsonReader.CurrentToken); + + await jsonReader.ReadAsync(); + Assert.AreEqual(jsonReader.TokenType, JsonToken.None); + Assert.AreEqual(null, jsonReader.CurrentToken); + } + } + + [Test] + public async Task ReadBytesAsync() + { + byte[] data = Encoding.UTF8.GetBytes("Hello world!"); + + JObject o = + new JObject( + new JProperty("Test1", data) + ); + + using (JTokenReader jsonReader = new JTokenReader(o)) + { + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); + + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); + Assert.AreEqual("Test1", jsonReader.Value); + + byte[] readBytes = await jsonReader.ReadAsBytesAsync(); + Assert.AreEqual(data, readBytes); + + Assert.IsTrue(await jsonReader.ReadAsync()); + Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType); + + Assert.IsFalse(await jsonReader.ReadAsync()); + Assert.AreEqual(JsonToken.None, jsonReader.TokenType); + } + } + + [Test] + public async Task ReadBytesFailureAsync() + { + await ExceptionAssert.ThrowsAsync(async () => + { + JObject o = + new JObject( + new JProperty("Test1", 1) + ); + + using (JTokenReader jsonReader = new JTokenReader(o)) + { + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); + + await jsonReader.ReadAsync(); + Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); + Assert.AreEqual("Test1", jsonReader.Value); + + await jsonReader.ReadAsBytesAsync(); + } + }, "Error reading bytes. Unexpected token: Integer. Path 'Test1'."); + } + + public class HasBytes + { + public byte[] Bytes { get; set; } + } + + [Test] + public async Task ReadAsDecimalIntAsync() + { + string json = @"{""Name"":1}"; + + JObject o = JObject.Parse(json); + + JsonReader reader = o.CreateReader(); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + await reader.ReadAsDecimalAsync(); + Assert.AreEqual(JsonToken.Float, reader.TokenType); + Assert.AreEqual(typeof(decimal), reader.ValueType); + Assert.AreEqual(1m, reader.Value); + } + + [Test] + public async Task ReadAsInt32IntAsync() + { + string json = @"{""Name"":1}"; + + JObject o = JObject.Parse(json); + + JTokenReader reader = (JTokenReader)o.CreateReader(); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + Assert.AreEqual(o, reader.CurrentToken); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + Assert.AreEqual(o.Property("Name"), reader.CurrentToken); + + await reader.ReadAsInt32Async(); + Assert.AreEqual(o["Name"], reader.CurrentToken); + Assert.AreEqual(JsonToken.Integer, reader.TokenType); + Assert.AreEqual(typeof(int), reader.ValueType); + Assert.AreEqual(1, reader.Value); + } + + [Test] + public async Task ReadAsInt32BadStringAsync() + { + string json = @"{""Name"":""hi""}"; + + JObject o = JObject.Parse(json); + + JsonReader reader = o.CreateReader(); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + await ExceptionAssert.ThrowsAsync(async () => { await reader.ReadAsInt32Async(); }, "Could not convert string to integer: hi. Path 'Name', line 1, position 12."); + } + + [Test] + public async Task ReadAsInt32BooleanAsync() + { + string json = @"{""Name"":true}"; + + JObject o = JObject.Parse(json); + + JsonReader reader = o.CreateReader(); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + await ExceptionAssert.ThrowsAsync(async () => { await reader.ReadAsInt32Async(); }, "Error reading integer. Unexpected token: Boolean. Path 'Name', line 1, position 12."); + } + + [Test] + public async Task ReadAsDecimalStringAsync() + { + string json = @"{""Name"":""1.1""}"; + + JObject o = JObject.Parse(json); + + JsonReader reader = o.CreateReader(); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + await reader.ReadAsDecimalAsync(); + Assert.AreEqual(JsonToken.Float, reader.TokenType); + Assert.AreEqual(typeof(decimal), reader.ValueType); + Assert.AreEqual(1.1m, reader.Value); + } + + [Test] + public async Task ReadAsDecimalBadStringAsync() + { + string json = @"{""Name"":""blah""}"; + + JObject o = JObject.Parse(json); + + JsonReader reader = o.CreateReader(); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + await ExceptionAssert.ThrowsAsync(async () => { await reader.ReadAsDecimalAsync(); }, "Could not convert string to decimal: blah. Path 'Name', line 1, position 14."); + } + + [Test] + public async Task ReadAsDecimalBooleanAsync() + { + string json = @"{""Name"":true}"; + + JObject o = JObject.Parse(json); + + JsonReader reader = o.CreateReader(); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + await ExceptionAssert.ThrowsAsync(async () => { await reader.ReadAsDecimalAsync(); }, "Error reading decimal. Unexpected token: Boolean. Path 'Name', line 1, position 12."); + } + + [Test] + public async Task ReadAsDecimalNullAsync() + { + string json = @"{""Name"":null}"; + + JObject o = JObject.Parse(json); + + JsonReader reader = o.CreateReader(); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.StartObject, reader.TokenType); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); + + await reader.ReadAsDecimalAsync(); + Assert.AreEqual(JsonToken.Null, reader.TokenType); + Assert.AreEqual(null, reader.ValueType); + Assert.AreEqual(null, reader.Value); + } + + [Test] + public async Task InitialPath_PropertyBase_PropertyTokenAsync() + { + JObject o = new JObject + { + { "prop1", true } + }; + + JTokenReader reader = new JTokenReader(o, "baseprop"); + + Assert.AreEqual("baseprop", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("baseprop", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("baseprop.prop1", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("baseprop.prop1", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("baseprop", reader.Path); + + Assert.IsFalse(await reader.ReadAsync()); + Assert.AreEqual("baseprop", reader.Path); + } + + [Test] + public async Task InitialPath_ArrayBase_PropertyTokenAsync() + { + JObject o = new JObject + { + { "prop1", true } + }; + + JTokenReader reader = new JTokenReader(o, "[0]"); + + Assert.AreEqual("[0]", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("[0]", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("[0].prop1", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("[0].prop1", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("[0]", reader.Path); + + Assert.IsFalse(await reader.ReadAsync()); + Assert.AreEqual("[0]", reader.Path); + } + + [Test] + public async Task InitialPath_PropertyBase_ArrayTokenAsync() + { + JArray a = new JArray + { + 1, 2 + }; + + JTokenReader reader = new JTokenReader(a, "baseprop"); + + Assert.AreEqual("baseprop", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("baseprop", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("baseprop[0]", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("baseprop[1]", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("baseprop", reader.Path); + + Assert.IsFalse(await reader.ReadAsync()); + Assert.AreEqual("baseprop", reader.Path); + } + + [Test] + public async Task InitialPath_ArrayBase_ArrayTokenAsync() + { + JArray a = new JArray + { + 1, 2 + }; + + JTokenReader reader = new JTokenReader(a, "[0]"); + + Assert.AreEqual("[0]", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("[0]", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("[0][0]", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("[0][1]", reader.Path); + + Assert.IsTrue(await reader.ReadAsync()); + Assert.AreEqual("[0]", reader.Path); + + Assert.IsFalse(await reader.ReadAsync()); + Assert.AreEqual("[0]", reader.Path); + } + + [Test] + public async Task ReadAsDouble_InvalidTokenAsync() + { + JArray a = new JArray + { + 1, 2 + }; + + JTokenReader reader = new JTokenReader(a); + + await ExceptionAssert.ThrowsAsync( + async () => { await reader.ReadAsDoubleAsync(); }, + "Error reading double. Unexpected token: StartArray. Path ''."); + } + + [Test] + public async Task ReadAsBoolean_InvalidTokenAsync() + { + JArray a = new JArray + { + 1, 2 + }; + + JTokenReader reader = new JTokenReader(a); + + await ExceptionAssert.ThrowsAsync( + async () => { await reader.ReadAsBooleanAsync(); }, + "Error reading boolean. Unexpected token: StartArray. Path ''."); + } + + [Test] + public async Task ReadAsDateTime_InvalidTokenAsync() + { + JArray a = new JArray + { + 1, 2 + }; + + JTokenReader reader = new JTokenReader(a); + + await ExceptionAssert.ThrowsAsync( + async () => { await reader.ReadAsDateTimeAsync(); }, + "Error reading date. Unexpected token: StartArray. Path ''."); + } + + [Test] + public async Task ReadAsDateTimeOffset_InvalidTokenAsync() + { + JArray a = new JArray + { + 1, 2 + }; + + JTokenReader reader = new JTokenReader(a); + + await ExceptionAssert.ThrowsAsync( + async () => { await reader.ReadAsDateTimeOffsetAsync(); }, + "Error reading date. Unexpected token: StartArray. Path ''."); + } + + [Test] + public async Task ReadAsDateTimeOffset_DateTimeAsync() + { + JValue v = new JValue(new DateTime(2001, 12, 12, 12, 12, 12, DateTimeKind.Utc)); + + JTokenReader reader = new JTokenReader(v); + + Assert.AreEqual(new DateTimeOffset(2001, 12, 12, 12, 12, 12, TimeSpan.Zero), await reader.ReadAsDateTimeOffsetAsync()); + } + + [Test] + public async Task ReadAsDateTimeOffset_StringAsync() + { + JValue v = new JValue("2012-01-24T03:50Z"); + + JTokenReader reader = new JTokenReader(v); + + Assert.AreEqual(new DateTimeOffset(2012, 1, 24, 3, 50, 0, TimeSpan.Zero), await reader.ReadAsDateTimeOffsetAsync()); + } + + [Test] + public async Task ReadAsDateTime_DateTimeOffsetAsync() + { + JValue v = new JValue(new DateTimeOffset(2012, 1, 24, 3, 50, 0, TimeSpan.Zero)); + + JTokenReader reader = new JTokenReader(v); + + Assert.AreEqual(new DateTime(2012, 1, 24, 3, 50, 0, DateTimeKind.Utc), await reader.ReadAsDateTimeAsync()); + } + + [Test] + public async Task ReadAsDateTime_StringAsync() + { + JValue v = new JValue("2012-01-24T03:50Z"); + + JTokenReader reader = new JTokenReader(v); + + Assert.AreEqual(new DateTime(2012, 1, 24, 3, 50, 0, DateTimeKind.Utc), await reader.ReadAsDateTimeAsync()); + } + + [Test] + public async Task ReadAsDouble_String_SuccessAsync() + { + JValue s = JValue.CreateString("123.4"); + + JTokenReader reader = new JTokenReader(s); + + Assert.AreEqual(123.4d, await reader.ReadAsDoubleAsync()); + } + + [Test] + public async Task ReadAsDouble_Null_SuccessAsync() + { + JValue n = JValue.CreateNull(); + + JTokenReader reader = new JTokenReader(n); + + Assert.AreEqual(null, await reader.ReadAsDoubleAsync()); + } + + [Test] + public async Task ReadAsDouble_Integer_SuccessAsync() + { + JValue n = new JValue(1); + + JTokenReader reader = new JTokenReader(n); + + Assert.AreEqual(1d, await reader.ReadAsDoubleAsync()); + } + +#if !PORTABLE || NETSTANDARD1_1 + [Test] + public async Task ReadAsBoolean_BigInteger_SuccessAsync() + { + JValue s = new JValue(BigInteger.Parse("99999999999999999999999999999999999999999999999999999999999999999999999999")); + + JTokenReader reader = new JTokenReader(s); + + Assert.AreEqual(true, await reader.ReadAsBooleanAsync()); + } +#endif + + [Test] + public async Task ReadAsBoolean_String_SuccessAsync() + { + JValue s = JValue.CreateString("true"); + + JTokenReader reader = new JTokenReader(s); + + Assert.AreEqual(true, await reader.ReadAsBooleanAsync()); + } + + [Test] + public async Task ReadAsBoolean_Null_SuccessAsync() + { + JValue n = JValue.CreateNull(); + + JTokenReader reader = new JTokenReader(n); + + Assert.AreEqual(null, await reader.ReadAsBooleanAsync()); + } + + [Test] + public async Task ReadAsBoolean_Integer_SuccessAsync() + { + JValue n = new JValue(1); + + JTokenReader reader = new JTokenReader(n); + + Assert.AreEqual(true, await reader.ReadAsBooleanAsync()); + } + + [Test] + public async Task ReadAsDateTime_Null_SuccessAsync() + { + JValue n = JValue.CreateNull(); + + JTokenReader reader = new JTokenReader(n); + + Assert.AreEqual(null, await reader.ReadAsDateTimeAsync()); + } + + [Test] + public async Task ReadAsDateTimeOffset_Null_SuccessAsync() + { + JValue n = JValue.CreateNull(); + + JTokenReader reader = new JTokenReader(n); + + Assert.AreEqual(null, await reader.ReadAsDateTimeOffsetAsync()); + } + + [Test] + public async Task ReadAsString_Integer_SuccessAsync() + { + JValue n = new JValue(1); + + JTokenReader reader = new JTokenReader(n); + + Assert.AreEqual("1", await reader.ReadAsStringAsync()); + } + + [Test] + public async Task ReadAsString_Guid_SuccessAsync() + { + JValue n = new JValue(new Uri("http://www.test.com")); + + JTokenReader reader = new JTokenReader(n); + + Assert.AreEqual("http://www.test.com", await reader.ReadAsStringAsync()); + } + + [Test] + public async Task ReadAsBytes_Integer_SuccessAsync() + { + JValue n = JValue.CreateNull(); + + JTokenReader reader = new JTokenReader(n); + + Assert.AreEqual(null, await reader.ReadAsBytesAsync()); + } + + [Test] + public async Task ReadAsBytes_ArrayAsync() + { + JArray a = new JArray + { + 1, 2 + }; + + JTokenReader reader = new JTokenReader(a); + + byte[] bytes = await reader.ReadAsBytesAsync(); + + Assert.AreEqual(2, bytes.Length); + Assert.AreEqual(1, bytes[0]); + Assert.AreEqual(2, bytes[1]); + } + + [Test] + public async Task ReadAsBytes_NullAsync() + { + JValue n = JValue.CreateNull(); + + JTokenReader reader = new JTokenReader(n); + + Assert.AreEqual(null, await reader.ReadAsBytesAsync()); + } + } +} + +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterAsyncTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterAsyncTests.cs new file mode 100644 index 00000000..7a6b84be --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenWriterAsyncTests.cs @@ -0,0 +1,391 @@ +#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 || PORTABLE40) + +using System; +#if !PORTABLE || NETSTANDARD1_1 +using System.Numerics; +#endif +using System.Text; +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif +using Newtonsoft.Json.Linq; +using System.Linq; +using System.Threading.Tasks; + +namespace Newtonsoft.Json.Tests.Linq +{ + [TestFixture] + public class JTokenWriterAsyncTests : TestFixtureBase + { + [Test] + public async Task ValueFormattingAsync() + { + byte[] data = Encoding.UTF8.GetBytes("Hello world."); + + JToken root; + using (JTokenWriter jsonWriter = new JTokenWriter()) + { + await jsonWriter.WriteStartArrayAsync(); + await jsonWriter.WriteValueAsync('@'); + await jsonWriter.WriteValueAsync("\r\n\t\f\b?{\\r\\n\"\'"); + await jsonWriter.WriteValueAsync(true); + await jsonWriter.WriteValueAsync(10); + await jsonWriter.WriteValueAsync(10.99); + await jsonWriter.WriteValueAsync(0.99); + await jsonWriter.WriteValueAsync(0.000000000000000001d); + await jsonWriter.WriteValueAsync(0.000000000000000001m); + await jsonWriter.WriteValueAsync((string)null); + await jsonWriter.WriteValueAsync("This is a string."); + await jsonWriter.WriteNullAsync(); + await jsonWriter.WriteUndefinedAsync(); + await jsonWriter.WriteValueAsync(data); + await jsonWriter.WriteEndArrayAsync(); + + root = jsonWriter.Token; + } + + CustomAssert.IsInstanceOfType(typeof(JArray), root); + Assert.AreEqual(13, root.Children().Count()); + Assert.AreEqual("@", (string)root[0]); + Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", (string)root[1]); + Assert.AreEqual(true, (bool)root[2]); + Assert.AreEqual(10, (int)root[3]); + Assert.AreEqual(10.99, (double)root[4]); + Assert.AreEqual(0.99, (double)root[5]); + Assert.AreEqual(0.000000000000000001d, (double)root[6]); + Assert.AreEqual(0.000000000000000001m, (decimal)root[7]); + Assert.AreEqual(null, (string)root[8]); + Assert.AreEqual("This is a string.", (string)root[9]); + Assert.AreEqual(null, ((JValue)root[10]).Value); + Assert.AreEqual(null, ((JValue)root[11]).Value); + Assert.AreEqual(data, (byte[])root[12]); + } + + [Test] + public async Task StateAsync() + { + using (JsonWriter jsonWriter = new JTokenWriter()) + { + Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); + + await jsonWriter.WriteStartObjectAsync(); + Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); + + await jsonWriter.WritePropertyNameAsync("CPU"); + Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); + + await jsonWriter.WriteValueAsync("Intel"); + Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); + + await jsonWriter.WritePropertyNameAsync("Drives"); + Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); + + await jsonWriter.WriteStartArrayAsync(); + Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); + + await jsonWriter.WriteValueAsync("DVD read/writer"); + Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); + +#if !PORTABLE || NETSTANDARD1_1 + await jsonWriter.WriteValueAsync(new BigInteger(123)); + Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); +#endif + + await jsonWriter.WriteValueAsync(new byte[0]); + Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); + + await jsonWriter.WriteEndAsync(); + Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); + + await jsonWriter.WriteEndObjectAsync(); + Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); + } + } + + [Test] + public async Task CurrentTokenAsync() + { + using (JTokenWriter jsonWriter = new JTokenWriter()) + { + Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); + Assert.AreEqual(null, jsonWriter.CurrentToken); + + await jsonWriter.WriteStartObjectAsync(); + Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); + Assert.AreEqual(jsonWriter.Token, jsonWriter.CurrentToken); + + JObject o = (JObject)jsonWriter.Token; + + await jsonWriter.WritePropertyNameAsync("CPU"); + Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); + Assert.AreEqual(o.Property("CPU"), jsonWriter.CurrentToken); + + await jsonWriter.WriteValueAsync("Intel"); + Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); + Assert.AreEqual(o["CPU"], jsonWriter.CurrentToken); + + await jsonWriter.WritePropertyNameAsync("Drives"); + Assert.AreEqual(WriteState.Property, jsonWriter.WriteState); + Assert.AreEqual(o.Property("Drives"), jsonWriter.CurrentToken); + + await jsonWriter.WriteStartArrayAsync(); + Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); + Assert.AreEqual(o["Drives"], jsonWriter.CurrentToken); + + JArray a = (JArray)jsonWriter.CurrentToken; + + await jsonWriter.WriteValueAsync("DVD read/writer"); + Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); + Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken); + +#if !PORTABLE || NETSTANDARD1_1 + await jsonWriter.WriteValueAsync(new BigInteger(123)); + Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); + Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken); +#endif + + await jsonWriter.WriteValueAsync(new byte[0]); + Assert.AreEqual(WriteState.Array, jsonWriter.WriteState); + Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken); + + await jsonWriter.WriteEndAsync(); + Assert.AreEqual(WriteState.Object, jsonWriter.WriteState); + Assert.AreEqual(a, jsonWriter.CurrentToken); + + await jsonWriter.WriteEndObjectAsync(); + Assert.AreEqual(WriteState.Start, jsonWriter.WriteState); + Assert.AreEqual(o, jsonWriter.CurrentToken); + } + } + + [Test] + public async Task WriteCommentAsync() + { + JTokenWriter writer = new JTokenWriter(); + + await writer.WriteStartArrayAsync(); + await writer.WriteCommentAsync("fail"); + await writer.WriteEndArrayAsync(); + + StringAssert.AreEqual(@"[ + /*fail*/]", writer.Token.ToString()); + } + +#if !PORTABLE || NETSTANDARD1_1 + [Test] + public async Task WriteBigIntegerAsync() + { + JTokenWriter writer = new JTokenWriter(); + + await writer.WriteStartArrayAsync(); + await writer.WriteValueAsync(new BigInteger(123)); + await writer.WriteEndArrayAsync(); + + JValue i = (JValue)writer.Token[0]; + + Assert.AreEqual(new BigInteger(123), i.Value); + Assert.AreEqual(JTokenType.Integer, i.Type); + + StringAssert.AreEqual(@"[ + 123 +]", writer.Token.ToString()); + } +#endif + + [Test] + public async Task WriteRawAsync() + { + JTokenWriter writer = new JTokenWriter(); + + await writer.WriteStartArrayAsync(); + await writer.WriteRawAsync("fail"); + await writer.WriteRawAsync("fail"); + await writer.WriteEndArrayAsync(); + + // this is a bug. See non-async equivalent test. + StringAssert.AreEqual(@"[ + fail, + fail +]", writer.Token.ToString()); + } + + [Test] + public async Task WriteTokenWithParentAsync() + { + JObject o = new JObject + { + ["prop1"] = new JArray(1), + ["prop2"] = 1 + }; + + JTokenWriter writer = new JTokenWriter(); + + await writer.WriteStartArrayAsync(); + + await writer.WriteTokenAsync(o.CreateReader()); + + Assert.AreEqual(WriteState.Array, writer.WriteState); + + await writer.WriteEndArrayAsync(); + + Console.WriteLine(writer.Token.ToString()); + + StringAssert.AreEqual(@"[ + { + ""prop1"": [ + 1 + ], + ""prop2"": 1 + } +]", writer.Token.ToString()); + } + + [Test] + public async Task WriteTokenWithPropertyParentAsync() + { + JValue v = new JValue(1); + + JTokenWriter writer = new JTokenWriter(); + + await writer.WriteStartObjectAsync(); + await writer.WritePropertyNameAsync("Prop1"); + + await writer.WriteTokenAsync(v.CreateReader()); + + Assert.AreEqual(WriteState.Object, writer.WriteState); + + await writer.WriteEndObjectAsync(); + + StringAssert.AreEqual(@"{ + ""Prop1"": 1 +}", writer.Token.ToString()); + } + + [Test] + public async Task WriteValueTokenWithParentAsync() + { + JValue v = new JValue(1); + + JTokenWriter writer = new JTokenWriter(); + + await writer.WriteStartArrayAsync(); + + await writer.WriteTokenAsync(v.CreateReader()); + + Assert.AreEqual(WriteState.Array, writer.WriteState); + + await writer.WriteEndArrayAsync(); + + StringAssert.AreEqual(@"[ + 1 +]", writer.Token.ToString()); + } + + [Test] + public async Task WriteEmptyTokenAsync() + { + JObject o = new JObject(); + JsonReader reader = o.CreateReader(); + while (reader.Read()) + { + } + + JTokenWriter writer = new JTokenWriter(); + + await writer.WriteStartArrayAsync(); + + await writer.WriteTokenAsync(reader); + + Assert.AreEqual(WriteState.Array, writer.WriteState); + + await writer.WriteEndArrayAsync(); + + StringAssert.AreEqual(@"[]", writer.Token.ToString()); + } + + [Test] + public async Task WriteRawValueAsync() + { + JTokenWriter writer = new JTokenWriter(); + + await writer.WriteStartArrayAsync(); + await writer.WriteRawValueAsync("fail"); + await writer.WriteRawValueAsync("fail"); + await writer.WriteEndArrayAsync(); + + StringAssert.AreEqual(@"[ + fail, + fail +]", writer.Token.ToString()); + } + + [Test] + public async Task WriteDuplicatePropertyNameAsync() + { + JTokenWriter writer = new JTokenWriter(); + + await writer.WriteStartObjectAsync(); + + await writer.WritePropertyNameAsync("prop1"); + await writer.WriteStartObjectAsync(); + await writer.WriteEndObjectAsync(); + + await writer.WritePropertyNameAsync("prop1"); + await writer.WriteStartArrayAsync(); + await writer.WriteEndArrayAsync(); + + await writer.WriteEndObjectAsync(); + + StringAssert.AreEqual(@"{ + ""prop1"": [] +}", writer.Token.ToString()); + } + + [Test] + public async Task DateTimeZoneHandlingAsync() + { + JTokenWriter writer = new JTokenWriter + { + DateTimeZoneHandling = DateTimeZoneHandling.Utc + }; + + await writer.WriteValueAsync(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified)); + + JValue value = (JValue)writer.Token; + DateTime dt = (DateTime)value.Value; + + Assert.AreEqual(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc), dt); + } + } +} + +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/JValueAsyncTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JValueAsyncTests.cs new file mode 100644 index 00000000..9a28890b --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Linq/JValueAsyncTests.cs @@ -0,0 +1,111 @@ +#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 || PORTABLE40) + +using System; +using System.IO; +using System.Threading.Tasks; +using System.Text; +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif +using Newtonsoft.Json.Linq; + +namespace Newtonsoft.Json.Tests.Linq +{ + [TestFixture] + public class JValueAsyncTests : TestFixtureBase + { + [Test] + public async Task FloatParseHandlingAsync() + { + JValue v = (JValue)await JToken.ReadFromAsync( + new JsonTextReader(new StringReader("9.9")) + { + FloatParseHandling = FloatParseHandling.Decimal + }); + + Assert.AreEqual(9.9m, v.Value); + Assert.AreEqual(typeof(decimal), v.Value.GetType()); + } + + public class Rate + { + public decimal Compoundings { get; set; } + } + + private readonly Rate _rate = new Rate { Compoundings = 12.166666666666666666666666667m }; + + + [Test] + public async Task ParseAndConvertDateTimeOffsetAsync() + { + var json = @"{ d: ""\/Date(0+0100)\/"" }"; + + using (var stringReader = new StringReader(json)) + using (var jsonReader = new JsonTextReader(stringReader)) + { + jsonReader.DateParseHandling = DateParseHandling.DateTimeOffset; + + var obj = await JObject.LoadAsync(jsonReader); + var d = (JValue)obj["d"]; + + CustomAssert.IsInstanceOfType(typeof(DateTimeOffset), d.Value); + TimeSpan offset = ((DateTimeOffset)d.Value).Offset; + Assert.AreEqual(TimeSpan.FromHours(1), offset); + + DateTimeOffset dateTimeOffset = (DateTimeOffset)d; + Assert.AreEqual(TimeSpan.FromHours(1), dateTimeOffset.Offset); + } + } + +#if !PORTABLE + +#endif + + [Test] + public async Task ParseIsoTimeZonesAsync() + { + DateTimeOffset expectedDate = new DateTimeOffset(2013, 08, 14, 4, 38, 31, TimeSpan.FromHours(12).Add(TimeSpan.FromMinutes(30))); + JsonTextReader reader = new JsonTextReader(new StringReader("'2013-08-14T04:38:31.000+1230'")); + reader.DateParseHandling = DateParseHandling.DateTimeOffset; + JValue date = (JValue)await JToken.ReadFromAsync(reader); + Assert.AreEqual(expectedDate, date.Value); + + DateTimeOffset expectedDate2 = new DateTimeOffset(2013, 08, 14, 4, 38, 31, TimeSpan.FromHours(12)); + JsonTextReader reader2 = new JsonTextReader(new StringReader("'2013-08-14T04:38:31.000+12'")); + reader2.DateParseHandling = DateParseHandling.DateTimeOffset; + JValue date2 = (JValue)await JToken.ReadFromAsync(reader2); + Assert.AreEqual(expectedDate2, date2.Value); + } + } +} + +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonAsyncTests.cs b/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonAsyncTests.cs new file mode 100644 index 00000000..fbcb8087 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonAsyncTests.cs @@ -0,0 +1,174 @@ +#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 || PORTABLE40) + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +#else +using NUnit.Framework; +#endif +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Tests.TestObjects.Organization; +using System.Linq; +using System.IO; + +namespace Newtonsoft.Json.Tests.Linq +{ + [TestFixture] + public class LinqToJsonAsyncTests : TestFixtureBase + { + [Test] + public async Task CommentsAndReadFromAsync() + { + StringReader textReader = new StringReader(@"[ + // hi + 1, + 2, + 3 +]"); + + JsonTextReader jsonReader = new JsonTextReader(textReader); + JArray a = (JArray)await JToken.ReadFromAsync(jsonReader, new JsonLoadSettings + { + CommentHandling = CommentHandling.Load + }); + + Assert.AreEqual(4, a.Count); + Assert.AreEqual(JTokenType.Comment, a[0].Type); + Assert.AreEqual(" hi", ((JValue)a[0]).Value); + } + + [Test] + public async Task CommentsAndReadFrom_IgnoreCommentsAsync() + { + StringReader textReader = new StringReader(@"[ + // hi + 1, + 2, + 3 +]"); + + JsonTextReader jsonReader = new JsonTextReader(textReader); + JArray a = (JArray)await JToken.ReadFromAsync(jsonReader); + + Assert.AreEqual(3, a.Count); + Assert.AreEqual(JTokenType.Integer, a[0].Type); + Assert.AreEqual(1L, ((JValue)a[0]).Value); + } + + [Test] + public async Task StartingCommentAndReadFromAsync() + { + StringReader textReader = new StringReader(@" +// hi +[ + 1, + 2, + 3 +]"); + + JsonTextReader jsonReader = new JsonTextReader(textReader); + JValue v = (JValue)await JToken.ReadFromAsync(jsonReader, new JsonLoadSettings + { + CommentHandling = CommentHandling.Load + }); + + Assert.AreEqual(JTokenType.Comment, v.Type); + + IJsonLineInfo lineInfo = v; + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(2, lineInfo.LineNumber); + Assert.AreEqual(5, lineInfo.LinePosition); + } + + [Test] + public async Task StartingCommentAndReadFrom_IgnoreCommentsAsync() + { + StringReader textReader = new StringReader(@" +// hi +[ + 1, + 2, + 3 +]"); + + JsonTextReader jsonReader = new JsonTextReader(textReader); + JArray a = (JArray)await JToken.ReadFromAsync(jsonReader, new JsonLoadSettings + { + CommentHandling = CommentHandling.Ignore + }); + + Assert.AreEqual(JTokenType.Array, a.Type); + + IJsonLineInfo lineInfo = a; + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(3, lineInfo.LineNumber); + Assert.AreEqual(1, lineInfo.LinePosition); + } + + [Test] + public async Task StartingUndefinedAndReadFromAsync() + { + StringReader textReader = new StringReader(@" +undefined +[ + 1, + 2, + 3 +]"); + + JsonTextReader jsonReader = new JsonTextReader(textReader); + JValue v = (JValue)await JToken.ReadFromAsync(jsonReader); + + Assert.AreEqual(JTokenType.Undefined, v.Type); + + IJsonLineInfo lineInfo = v; + Assert.AreEqual(true, lineInfo.HasLineInfo()); + Assert.AreEqual(2, lineInfo.LineNumber); + Assert.AreEqual(9, lineInfo.LinePosition); + } + + [Test] + public async Task StartingEndArrayAndReadFromAsync() + { + StringReader textReader = new StringReader(@"[]"); + + JsonTextReader jsonReader = new JsonTextReader(textReader); + await jsonReader.ReadAsync(); + await jsonReader.ReadAsync(); + + await ExceptionAssert.ThrowsAsync(async () => await JToken.ReadFromAsync(jsonReader), @"Error reading JToken from JsonReader. Unexpected token: EndArray. Path '', line 1, position 2."); + } + } +} + +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable.csproj index a103c53d..bdfff46e 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.Portable.csproj @@ -143,6 +143,14 @@ + + + + + + + + diff --git a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj index c892f073..786510cb 100644 --- a/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj +++ b/Src/Newtonsoft.Json.Tests/Newtonsoft.Json.Tests.csproj @@ -232,6 +232,14 @@ + + + + + + + + diff --git a/Src/Newtonsoft.Json/JsonReader.Async.cs b/Src/Newtonsoft.Json/JsonReader.Async.cs index 4ae6b2e0..060c6982 100644 --- a/Src/Newtonsoft.Json/JsonReader.Async.cs +++ b/Src/Newtonsoft.Json/JsonReader.Async.cs @@ -204,6 +204,31 @@ namespace Newtonsoft.Json { return cancellationToken.CancelIfRequestedAsync() ?? Task.FromResult(ReadAsString()); } + + internal async Task ReadAndMoveToContentAsync(CancellationToken cancellationToken) + { + return await ReadAsync(cancellationToken).ConfigureAwait(false) && await MoveToContentAsync(cancellationToken).ConfigureAwait(false); + } + + internal async Task MoveToContentAsync(CancellationToken cancellationToken) + { + while (true) + { + switch (TokenType) + { + case JsonToken.None: + case JsonToken.Comment: + if (!await ReadAsync(cancellationToken).ConfigureAwait(false)) + { + return false; + } + + break; + default: + return true; + } + } + } } } diff --git a/Src/Newtonsoft.Json/JsonTextWriter.Async.cs b/Src/Newtonsoft.Json/JsonTextWriter.Async.cs index 4f0a281f..8223af64 100644 --- a/Src/Newtonsoft.Json/JsonTextWriter.Async.cs +++ b/Src/Newtonsoft.Json/JsonTextWriter.Async.cs @@ -436,7 +436,7 @@ namespace Newtonsoft.Json return _safeAsync ? DoWriteStartConstructorAsync(name, cancellationToken) : base.WriteStartConstructorAsync(name, cancellationToken); } - private async Task DoWriteStartConstructorAsync(string name, CancellationToken cancellationToken) + internal async Task DoWriteStartConstructorAsync(string name, CancellationToken cancellationToken) { await InternalWriteStartAsync(JsonToken.StartConstructor, JsonContainerType.Constructor, cancellationToken).ConfigureAwait(false); diff --git a/Src/Newtonsoft.Json/JsonWriter.Async.cs b/Src/Newtonsoft.Json/JsonWriter.Async.cs index 61a9f17f..add1ac6b 100644 --- a/Src/Newtonsoft.Json/JsonWriter.Async.cs +++ b/Src/Newtonsoft.Json/JsonWriter.Async.cs @@ -26,7 +26,6 @@ #if !(NET20 || NET35 || NET40 || PORTABLE40) using System; -using System.Diagnostics; using System.Globalization; using System.Threading; #if !PORTABLE || NETSTANDARD1_1 @@ -699,6 +698,30 @@ namespace Newtonsoft.Json && await reader.ReadAsync(cancellationToken).ConfigureAwait(false)); } + // For internal use, when we know the writer does not offer true async support (e.g. when backed + // by a StringWriter) and therefore async write methods are always in practice just a less efficient + // path through the sync version. + internal async Task WriteTokenSyncReadingAsync(JsonReader reader, CancellationToken cancellationToken) + { + int initialDepth = CalculateWriteTokenDepth(reader); + + do + { + // write a JValue date when the constructor is for a date + if (reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) + { + WriteConstructorDate(reader); + } + else + { + WriteToken(reader.TokenType, reader.Value); + } + } while ( + // stop if we have reached the end of the token being read + initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0) + && await reader.ReadAsync(cancellationToken).ConfigureAwait(false)); + } + private async Task WriteConstructorDateAsync(JsonReader reader, CancellationToken cancellationToken) { if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) diff --git a/Src/Newtonsoft.Json/Linq/JArray.Async.cs b/Src/Newtonsoft.Json/Linq/JArray.Async.cs new file mode 100644 index 00000000..fa299af9 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JArray.Async.cs @@ -0,0 +1,103 @@ +#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 || PORTABLE40) + +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + public partial class JArray + { + /// + /// Writes this token to a asynchronously. + /// + /// A into which this method will write. + /// The token to monitor for cancellation requests. + /// A collection of which will be used when writing the token. + /// A that represents the asynchronous write operation. + public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) + { + await writer.WriteStartArrayAsync(cancellationToken).ConfigureAwait(false); + + for (int i = 0; i < _values.Count; i++) + { + await _values[i].WriteToAsync(writer, cancellationToken, converters).ConfigureAwait(false); + } + + await writer.WriteEndArrayAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Asynchronously loads a from a . + /// + /// A that will be read for the content of the . + /// If this is null, default load settings will be used. + /// The token to monitor for cancellation requests. The default value is . + /// A representing the asynchronous load. The property contains the JSON that was read from the specified . + public new static Task LoadAsync(JsonReader reader, CancellationToken cancellationToken = default(CancellationToken)) + { + return LoadAsync(reader, null, cancellationToken); + } + + /// + /// Asynchronously loads a from a . + /// + /// A that will be read for the content of the . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// The token to monitor for cancellation requests. The default value is . + /// A representing the asynchronous load. The property contains the JSON that was read from the specified . + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default(CancellationToken)) + { + if (reader.TokenType == JsonToken.None) + { + if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader."); + } + } + + await reader.MoveToContentAsync(cancellationToken).ConfigureAwait(false); + + if (reader.TokenType != JsonToken.StartArray) + { + throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + JArray a = new JArray(); + a.SetLineInfo(reader as IJsonLineInfo, settings); + + await a.ReadTokenFromAsync(reader, settings, cancellationToken).ConfigureAwait(false); + + return a; + } + } +} + +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JArray.cs b/Src/Newtonsoft.Json/Linq/JArray.cs index cdb8b5c1..c6c117f3 100644 --- a/Src/Newtonsoft.Json/Linq/JArray.cs +++ b/Src/Newtonsoft.Json/Linq/JArray.cs @@ -38,7 +38,7 @@ namespace Newtonsoft.Json.Linq /// /// /// - public class JArray : JContainer, IList + public partial class JArray : JContainer, IList { private readonly List _values = new List(); diff --git a/Src/Newtonsoft.Json/Linq/JConstructor.Async.cs b/Src/Newtonsoft.Json/Linq/JConstructor.Async.cs new file mode 100644 index 00000000..df63d818 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JConstructor.Async.cs @@ -0,0 +1,106 @@ +#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 || PORTABLE40) + +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + public partial class JConstructor + { + /// + /// Writes this token to a asynchronously. + /// + /// A into which this method will write. + /// The token to monitor for cancellation requests. + /// A collection of which will be used when writing the token. + /// A that represents the asynchronous write operation. + public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) + { + await writer.WriteStartConstructorAsync(_name, cancellationToken).ConfigureAwait(false); + + for (int i = 0; i < _values.Count; i++) + { + await _values[i].WriteToAsync(writer, converters).ConfigureAwait(false); + } + + await writer.WriteEndConstructorAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Asynchronously loads a from a . + /// + /// A that will be read for the content of the . + /// The token to monitor for cancellation requests. The default value is . + /// + /// A that represents the asynchronous load. The + /// property returns a that contains the JSON that was read from the specified . + public new static Task LoadAsync(JsonReader reader, CancellationToken cancellationToken = default(CancellationToken)) + { + return LoadAsync(reader, null, cancellationToken); + } + + /// + /// Asynchronously loads a from a . + /// + /// A that will be read for the content of the . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// The token to monitor for cancellation requests. The default value is . + /// + /// A that represents the asynchronous load. The + /// property returns a that contains the JSON that was read from the specified . + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default(CancellationToken)) + { + if (reader.TokenType == JsonToken.None) + { + if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader."); + } + } + + await reader.MoveToContentAsync(cancellationToken).ConfigureAwait(false); + + if (reader.TokenType != JsonToken.StartConstructor) + { + throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + JConstructor c = new JConstructor((string)reader.Value); + c.SetLineInfo(reader as IJsonLineInfo, settings); + + await c.ReadTokenFromAsync(reader, settings, cancellationToken).ConfigureAwait(false); + + return c; + } + } +} + +#endif diff --git a/Src/Newtonsoft.Json/Linq/JConstructor.cs b/Src/Newtonsoft.Json/Linq/JConstructor.cs index b66004ae..ff7412d8 100644 --- a/Src/Newtonsoft.Json/Linq/JConstructor.cs +++ b/Src/Newtonsoft.Json/Linq/JConstructor.cs @@ -34,7 +34,7 @@ namespace Newtonsoft.Json.Linq /// /// Represents a JSON constructor. /// - public class JConstructor : JContainer + public partial class JConstructor : JContainer { private string _name; private readonly List _values = new List(); @@ -164,9 +164,10 @@ namespace Newtonsoft.Json.Linq { writer.WriteStartConstructor(_name); - foreach (JToken token in Children()) + int count = _values.Count; + for (int i = 0; i < count; i++) { - token.WriteTo(writer, converters); + _values[i].WriteTo(writer, converters); } writer.WriteEndConstructor(); diff --git a/Src/Newtonsoft.Json/Linq/JContainer.Async.cs b/Src/Newtonsoft.Json/Linq/JContainer.Async.cs new file mode 100644 index 00000000..131e566a --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JContainer.Async.cs @@ -0,0 +1,175 @@ +#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 || PORTABLE40) + +using System; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + public abstract partial class JContainer + { + internal async Task ReadTokenFromAsync(JsonReader reader, JsonLoadSettings options, CancellationToken cancellationToken = default(CancellationToken)) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + int startDepth = reader.Depth; + + if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + throw JsonReaderException.Create(reader, "Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); + } + + await ReadContentFromAsync(reader, options, cancellationToken).ConfigureAwait(false); + + if (reader.Depth > startDepth) + { + throw JsonReaderException.Create(reader, "Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); + } + } + + private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default(CancellationToken)) + { + IJsonLineInfo lineInfo = reader as IJsonLineInfo; + + JContainer parent = this; + + do + { + if ((parent as JProperty)?.Value != null) + { + if (parent == this) + { + return; + } + + parent = parent.Parent; + } + + switch (reader.TokenType) + { + case JsonToken.None: + // new reader. move to actual content + break; + case JsonToken.StartArray: + JArray a = new JArray(); + a.SetLineInfo(lineInfo, settings); + parent.Add(a); + parent = a; + break; + + case JsonToken.EndArray: + if (parent == this) + { + return; + } + + parent = parent.Parent; + break; + case JsonToken.StartObject: + JObject o = new JObject(); + o.SetLineInfo(lineInfo, settings); + parent.Add(o); + parent = o; + break; + case JsonToken.EndObject: + if (parent == this) + { + return; + } + + parent = parent.Parent; + break; + case JsonToken.StartConstructor: + JConstructor constructor = new JConstructor(reader.Value.ToString()); + constructor.SetLineInfo(lineInfo, settings); + parent.Add(constructor); + parent = constructor; + break; + case JsonToken.EndConstructor: + if (parent == this) + { + return; + } + + parent = parent.Parent; + break; + case JsonToken.String: + case JsonToken.Integer: + case JsonToken.Float: + case JsonToken.Date: + case JsonToken.Boolean: + case JsonToken.Bytes: + JValue v = new JValue(reader.Value); + v.SetLineInfo(lineInfo, settings); + parent.Add(v); + break; + case JsonToken.Comment: + if (settings != null && settings.CommentHandling == CommentHandling.Load) + { + v = JValue.CreateComment(reader.Value.ToString()); + v.SetLineInfo(lineInfo, settings); + parent.Add(v); + } + break; + case JsonToken.Null: + v = JValue.CreateNull(); + v.SetLineInfo(lineInfo, settings); + parent.Add(v); + break; + case JsonToken.Undefined: + v = JValue.CreateUndefined(); + v.SetLineInfo(lineInfo, settings); + parent.Add(v); + break; + case JsonToken.PropertyName: + string propertyName = reader.Value.ToString(); + JProperty property = new JProperty(propertyName); + property.SetLineInfo(lineInfo, settings); + JObject parentObject = (JObject)parent; + // handle multiple properties with the same name in JSON + JProperty existingPropertyWithName = parentObject.Property(propertyName); + if (existingPropertyWithName == null) + { + parent.Add(property); + } + else + { + existingPropertyWithName.Replace(property); + } + parent = property; + break; + default: + throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + } while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)); + } + } +} + +#endif diff --git a/Src/Newtonsoft.Json/Linq/JContainer.cs b/Src/Newtonsoft.Json/Linq/JContainer.cs index 1b3d5ddb..144dbaf5 100644 --- a/Src/Newtonsoft.Json/Linq/JContainer.cs +++ b/Src/Newtonsoft.Json/Linq/JContainer.cs @@ -45,7 +45,7 @@ namespace Newtonsoft.Json.Linq /// /// Represents a token that can contain other tokens. /// - public abstract class JContainer : JToken, IList + public abstract partial class JContainer : JToken, IList #if !(DOTNET || PORTABLE || PORTABLE40) , ITypedList, IBindingList #endif diff --git a/Src/Newtonsoft.Json/Linq/JObject.Async.cs b/Src/Newtonsoft.Json/Linq/JObject.Async.cs new file mode 100644 index 00000000..fe2fc644 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JObject.Async.cs @@ -0,0 +1,108 @@ +#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 || PORTABLE40) + +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + public partial class JObject + { + /// + /// Writes this token to a asynchronously. + /// + /// A into which this method will write. + /// The token to monitor for cancellation requests. + /// A collection of which will be used when writing the token. + /// A that represents the asynchronous write operation. + public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) + { + await writer.WriteStartObjectAsync(cancellationToken).ConfigureAwait(false); + + for (int i = 0; i < _properties.Count; i++) + { + await _properties[i].WriteToAsync(writer, converters).ConfigureAwait(false); + } + + await writer.WriteEndObjectAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Asynchronously loads a from a . + /// + /// A that will be read for the content of the . + /// The token to monitor for cancellation requests. The default value is . + /// + /// A that represents the asynchronous load. The + /// property returns a that contains the JSON that was read from the specified . + public new static Task LoadAsync(JsonReader reader, CancellationToken cancellationToken = default(CancellationToken)) + { + return LoadAsync(reader, null, cancellationToken); + } + + /// + /// Asynchronously loads a from a . + /// + /// A that will be read for the content of the . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// The token to monitor for cancellation requests. The default value is . + /// + /// A that represents the asynchronous load. The + /// property returns a that contains the JSON that was read from the specified . + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default(CancellationToken)) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + + if (reader.TokenType == JsonToken.None) + { + if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader."); + } + } + + await reader.MoveToContentAsync(cancellationToken).ConfigureAwait(false); + + if (reader.TokenType != JsonToken.StartObject) + { + throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + JObject o = new JObject(); + o.SetLineInfo(reader as IJsonLineInfo, settings); + + await o.ReadTokenFromAsync(reader, settings, cancellationToken).ConfigureAwait(false); + + return o; + } + } +} + +#endif diff --git a/Src/Newtonsoft.Json/Linq/JObject.cs b/Src/Newtonsoft.Json/Linq/JObject.cs index da76cd63..9c0c8e58 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.cs @@ -52,7 +52,7 @@ namespace Newtonsoft.Json.Linq /// /// /// - public class JObject : JContainer, IDictionary, INotifyPropertyChanged + public partial class JObject : JContainer, IDictionary, INotifyPropertyChanged #if !(DOTNET || PORTABLE40 || PORTABLE) , ICustomTypeDescriptor #endif diff --git a/Src/Newtonsoft.Json/Linq/JProperty.Async.cs b/Src/Newtonsoft.Json/Linq/JProperty.Async.cs new file mode 100644 index 00000000..414d6335 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JProperty.Async.cs @@ -0,0 +1,107 @@ +#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 || PORTABLE40) + +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + public partial class JProperty + { + /// + /// Writes this token to a asynchronously. + /// + /// A into which this method will write. + /// The token to monitor for cancellation requests. + /// A collection of which will be used when writing the token. + /// A that represents the asynchronous write operation. + public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) + { + await writer.WritePropertyNameAsync(_name, cancellationToken).ConfigureAwait(false); + + JToken value = Value; + if (value != null) + { + await value.WriteToAsync(writer, cancellationToken, converters).ConfigureAwait(false); + } + else + { + await writer.WriteNullAsync(cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Asynchronously loads a from a . + /// + /// A that will be read for the content of the . + /// The token to monitor for cancellation requests. The default value is . + /// A representing the asynchronous creation. The + /// property returns a that contains the JSON that was read from the specified . + public new static Task LoadAsync(JsonReader reader, CancellationToken cancellationToken = default(CancellationToken)) + { + return LoadAsync(reader, null, cancellationToken); + } + + /// + /// Asynchronously loads a from a . + /// + /// A that will be read for the content of the . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// The token to monitor for cancellation requests. The default value is . + /// A representing the asynchronous creation. The + /// property returns a that contains the JSON that was read from the specified . + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default(CancellationToken)) + { + if (reader.TokenType == JsonToken.None) + { + if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader."); + } + } + + await reader.MoveToContentAsync(cancellationToken).ConfigureAwait(false); + + if (reader.TokenType != JsonToken.PropertyName) + { + throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + + JProperty p = new JProperty((string)reader.Value); + p.SetLineInfo(reader as IJsonLineInfo, settings); + + await p.ReadTokenFromAsync(reader, settings, cancellationToken).ConfigureAwait(false); + + return p; + } + } +} + +#endif diff --git a/Src/Newtonsoft.Json/Linq/JProperty.cs b/Src/Newtonsoft.Json/Linq/JProperty.cs index c0779528..d6b1a6f9 100644 --- a/Src/Newtonsoft.Json/Linq/JProperty.cs +++ b/Src/Newtonsoft.Json/Linq/JProperty.cs @@ -35,7 +35,7 @@ namespace Newtonsoft.Json.Linq /// /// Represents a JSON property. /// - public class JProperty : JContainer + public partial class JProperty : JContainer { #region JPropertyList private class JPropertyList : IList diff --git a/Src/Newtonsoft.Json/Linq/JRaw.Async.cs b/Src/Newtonsoft.Json/Linq/JRaw.Async.cs new file mode 100644 index 00000000..4458bd7e --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JRaw.Async.cs @@ -0,0 +1,57 @@ +#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 || PORTABLE40) + +using System.Globalization; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Newtonsoft.Json.Linq +{ + public partial class JRaw + { + /// + /// Asynchronously creates an instance of with the content of the reader's current token. + /// + /// The reader. + /// The token to monitor for cancellation requests. The default value is . + /// A representing the asynchronous creation. The + /// property returns an instance of with the content of the reader's current token. + public static async Task CreateAsync(JsonReader reader, CancellationToken cancellationToken = default(CancellationToken)) + { + using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) + using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) + { + await jsonWriter.WriteTokenSyncReadingAsync(reader, cancellationToken).ConfigureAwait(false); + + return new JRaw(sw.ToString()); + } + } + } +} + +#endif diff --git a/Src/Newtonsoft.Json/Linq/JRaw.cs b/Src/Newtonsoft.Json/Linq/JRaw.cs index fec5a57d..9acc240f 100644 --- a/Src/Newtonsoft.Json/Linq/JRaw.cs +++ b/Src/Newtonsoft.Json/Linq/JRaw.cs @@ -31,7 +31,7 @@ namespace Newtonsoft.Json.Linq /// /// Represents a raw JSON string. /// - public class JRaw : JValue + public partial class JRaw : JValue { /// /// Initializes a new instance of the class from another object. diff --git a/Src/Newtonsoft.Json/Linq/JToken.Async.cs b/Src/Newtonsoft.Json/Linq/JToken.Async.cs new file mode 100644 index 00000000..63e04101 --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JToken.Async.cs @@ -0,0 +1,178 @@ +#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 || PORTABLE40) + +using System; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + public abstract partial class JToken + { + /// + /// Writes this token to a asynchronously. + /// + /// A into which this method will write. + /// The token to monitor for cancellation requests. + /// A collection of which will be used when writing the token. + /// A that represents the asynchronous write operation. + public virtual Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) + { + throw new NotImplementedException(); + } + + /// + /// Writes this token to a asynchronously. + /// + /// A into which this method will write. + /// A collection of which will be used when writing the token. + /// A that represents the asynchronous write operation. + public Task WriteToAsync(JsonWriter writer, params JsonConverter[] converters) + { + return WriteToAsync(writer, default(CancellationToken), converters); + } + + /// + /// Asynchronously creates a from a . + /// + /// An positioned at the token to read into this . + /// The token to monitor for cancellation requests. The default value is . + /// + /// A that represents the asynchronous creation. The + /// property returns a that contains + /// the token and its descendant tokens + /// that were read from the reader. The runtime type of the token is determined + /// by the token type of the first token encountered in the reader. + /// + public static Task ReadFromAsync(JsonReader reader, CancellationToken cancellationToken = default(CancellationToken)) + { + return ReadFromAsync(reader, null, cancellationToken); + } + + /// + /// Asynchronously creates a from a . + /// + /// An positioned at the token to read into this . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// The token to monitor for cancellation requests. The default value is . + /// + /// A that represents the asynchronous creation. The + /// property returns a that contains + /// the token and its descendant tokens + /// that were read from the reader. The runtime type of the token is determined + /// by the token type of the first token encountered in the reader. + /// + public static async Task ReadFromAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default(CancellationToken)) + { + ValidationUtils.ArgumentNotNull(reader, nameof(reader)); + + if (reader.TokenType == JsonToken.None) + { + if (!await (settings != null && settings.CommentHandling == CommentHandling.Ignore ? reader.ReadAndMoveToContentAsync(cancellationToken) : reader.ReadAsync(cancellationToken)).ConfigureAwait(false)) + { + throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader."); + } + } + + IJsonLineInfo lineInfo = reader as IJsonLineInfo; + + switch (reader.TokenType) + { + case JsonToken.StartObject: + return await JObject.LoadAsync(reader, settings, cancellationToken).ConfigureAwait(false); + case JsonToken.StartArray: + return await JArray.LoadAsync(reader, settings, cancellationToken).ConfigureAwait(false); + case JsonToken.StartConstructor: + return await JConstructor.LoadAsync(reader, settings, cancellationToken).ConfigureAwait(false); + case JsonToken.PropertyName: + return await JProperty.LoadAsync(reader, settings, cancellationToken).ConfigureAwait(false); + case JsonToken.String: + case JsonToken.Integer: + case JsonToken.Float: + case JsonToken.Date: + case JsonToken.Boolean: + case JsonToken.Bytes: + JValue v = new JValue(reader.Value); + v.SetLineInfo(lineInfo, settings); + return v; + case JsonToken.Comment: + v = JValue.CreateComment(reader.Value.ToString()); + v.SetLineInfo(lineInfo, settings); + return v; + case JsonToken.Null: + v = JValue.CreateNull(); + v.SetLineInfo(lineInfo, settings); + return v; + case JsonToken.Undefined: + v = JValue.CreateUndefined(); + v.SetLineInfo(lineInfo, settings); + return v; + default: + throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader. Unexpected token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + } + } + + /// + /// Asynchronously creates a from a . + /// + /// A positioned at the token to read into this . + /// The token to monitor for cancellation requests. The default value is . + /// + /// A that represents the asynchronous creation. The + /// property returns a that contains the token and its descendant tokens + /// that were read from the reader. The runtime type of the token is determined + /// by the token type of the first token encountered in the reader. + /// + public static Task LoadAsync(JsonReader reader, CancellationToken cancellationToken = default(CancellationToken)) + { + return LoadAsync(reader, null, cancellationToken); + } + + /// + /// Asynchronously creates a from a . + /// + /// A positioned at the token to read into this . + /// The used to load the JSON. + /// If this is null, default load settings will be used. + /// The token to monitor for cancellation requests. The default value is . + /// + /// A that represents the asynchronous creation. The + /// property returns a that contains the token and its descendant tokens + /// that were read from the reader. The runtime type of the token is determined + /// by the token type of the first token encountered in the reader. + /// + public static Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default(CancellationToken)) + { + return ReadFromAsync(reader, settings, cancellationToken); + } + } +} + +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 5e79dc98..b711e3a7 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -51,7 +51,7 @@ namespace Newtonsoft.Json.Linq /// /// Represents an abstract JSON token. /// - public abstract class JToken : IJEnumerable, IJsonLineInfo + public abstract partial class JToken : IJEnumerable, IJsonLineInfo #if !(DOTNET || PORTABLE40 || PORTABLE) , ICloneable #endif diff --git a/Src/Newtonsoft.Json/Linq/JTokenWriter.Async.cs b/Src/Newtonsoft.Json/Linq/JTokenWriter.Async.cs new file mode 100644 index 00000000..e49dd6fb --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JTokenWriter.Async.cs @@ -0,0 +1,53 @@ +#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 || PORTABLE40) + +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + public partial class JTokenWriter + { + // This is the only method that can benefit from Task-based asynchronicity, and that only when + // the reader provides it. + internal override Task WriteTokenAsync(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments, CancellationToken cancellationToken) + { + // Since JTokenReader is a common target (and with an optimised path) and since it can't + // read truly async, catch that case. + if (reader is JTokenReader) + { + WriteToken(reader, writeChildren, writeDateConstructorAsDate, writeComments); + return AsyncUtils.CompletedTask; + } + + return WriteTokenSyncReadingAsync(reader, cancellationToken); + } + } +} + +#endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs index f40d0ea8..72abd975 100644 --- a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs +++ b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs @@ -35,7 +35,7 @@ namespace Newtonsoft.Json.Linq /// /// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data. /// - public class JTokenWriter : JsonWriter + public partial class JTokenWriter : JsonWriter { private JContainer _token; private JContainer _parent; diff --git a/Src/Newtonsoft.Json/Linq/JValue.Async.cs b/Src/Newtonsoft.Json/Linq/JValue.Async.cs new file mode 100644 index 00000000..fb6327eb --- /dev/null +++ b/Src/Newtonsoft.Json/Linq/JValue.Async.cs @@ -0,0 +1,138 @@ +#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 || PORTABLE40) + +using System; +using System.Globalization; +#if !PORTABLE || NETSTANDARD1_1 +using System.Numerics; +#endif +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json.Utilities; + +namespace Newtonsoft.Json.Linq +{ + public partial class JValue + { + /// + /// Writes this token to a asynchronously. + /// + /// A into which this method will write. + /// The token to monitor for cancellation requests. + /// A collection of which will be used when writing the token. + /// A that represents the asynchronous write operation. + public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) + { + if (converters != null && converters.Length > 0 && _value != null) + { + JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); + if (matchingConverter != null && matchingConverter.CanWrite) + { + // TODO: Call WriteJsonAsync when it exists. + matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault()); + return AsyncUtils.CompletedTask; + } + } + + switch (_valueType) + { + case JTokenType.Comment: + return writer.WriteCommentAsync(_value != null ? _value.ToString() : null, cancellationToken); + case JTokenType.Raw: + return writer.WriteRawValueAsync(_value != null ? _value.ToString() : null, cancellationToken); + case JTokenType.Null: + return writer.WriteNullAsync(cancellationToken); + case JTokenType.Undefined: + return writer.WriteUndefinedAsync(cancellationToken); + case JTokenType.Integer: + if (_value is int) + { + return writer.WriteValueAsync((int)_value, cancellationToken); + } + + if (_value is long) + { + return writer.WriteValueAsync((long)_value, cancellationToken); + } + + if (_value is ulong) + { + return writer.WriteValueAsync((ulong)_value, cancellationToken); + } + +#if !(PORTABLE) || NETSTANDARD1_1 + if (_value is BigInteger) + { + return writer.WriteValueAsync((BigInteger)_value, cancellationToken); + } +#endif + + return writer.WriteValueAsync(Convert.ToInt64(_value, CultureInfo.InvariantCulture), cancellationToken); + case JTokenType.Float: + if (_value is decimal) + { + return writer.WriteValueAsync((decimal)_value, cancellationToken); + } + + if (_value is double) + { + return writer.WriteValueAsync((double)_value, cancellationToken); + } + + if (_value is float) + { + return writer.WriteValueAsync((float)_value, cancellationToken); + } + + return writer.WriteValueAsync(Convert.ToDouble(_value, CultureInfo.InvariantCulture), cancellationToken); + case JTokenType.String: + return writer.WriteValueAsync(_value != null ? _value.ToString() : null, cancellationToken); + case JTokenType.Boolean: + return writer.WriteValueAsync(Convert.ToBoolean(_value, CultureInfo.InvariantCulture), cancellationToken); + case JTokenType.Date: + if (_value is DateTimeOffset) + { + return writer.WriteValueAsync((DateTimeOffset)_value, cancellationToken); + } + + return writer.WriteValueAsync(Convert.ToDateTime(_value, CultureInfo.InvariantCulture), cancellationToken); + case JTokenType.Bytes: + return writer.WriteValueAsync((byte[])_value, cancellationToken); + case JTokenType.Guid: + return writer.WriteValueAsync(_value != null ? (Guid?)_value : null, cancellationToken); + case JTokenType.TimeSpan: + return writer.WriteValueAsync(_value != null ? (TimeSpan?)_value : null, cancellationToken); + case JTokenType.Uri: + return writer.WriteValueAsync((Uri)_value, cancellationToken); + } + + throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", _valueType, "Unexpected token type."); + } + } +} + +#endif diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs index bf2a7643..65defa49 100644 --- a/Src/Newtonsoft.Json/Linq/JValue.cs +++ b/Src/Newtonsoft.Json/Linq/JValue.cs @@ -42,7 +42,7 @@ namespace Newtonsoft.Json.Linq /// /// Represents a value in JSON (string, integer, date, etc). /// - public class JValue : JToken, IEquatable, IFormattable, IComparable, IComparable + public partial class JValue : JToken, IEquatable, IFormattable, IComparable, IComparable #if !PORTABLE , IConvertible #endif diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Portable.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.Portable.csproj index 986e37b9..4a2d78a6 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Portable.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Portable.csproj @@ -113,14 +113,20 @@ + + + + + + @@ -136,11 +142,14 @@ + + + diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index e814725a..0b3ea340 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -115,11 +115,17 @@ + + + + + + @@ -137,11 +143,14 @@ + + +