diff --git a/Manatee.Json.Performance/Manatee.Json.Performance.csproj b/Manatee.Json.Performance/Manatee.Json.Performance.csproj deleted file mode 100644 index d6f7360..0000000 --- a/Manatee.Json.Performance/Manatee.Json.Performance.csproj +++ /dev/null @@ -1,108 +0,0 @@ - - - - Debug - AnyCPU - {2F8A54FB-B395-4BE4-9DF8-D9A13BF1D4F5} - Library - Properties - Manatee.Json.Performance - Manatee.Json.Performance - v4.5 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages - False - UnitTest - - ..\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - true - - - Manatee.Json.snk - - - - - - - - - - - - - - - - - - Always - - - - - - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7} - Manatee.Json-4.5 - - - - - - - False - - - False - - - False - - - False - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - \ No newline at end of file diff --git a/Manatee.Json.Performance/Manatee.Json.snk b/Manatee.Json.Performance/Manatee.Json.snk deleted file mode 100644 index da49a45..0000000 Binary files a/Manatee.Json.Performance/Manatee.Json.snk and /dev/null differ diff --git a/Manatee.Json.Performance/Properties/AssemblyInfo.cs b/Manatee.Json.Performance/Properties/AssemblyInfo.cs deleted file mode 100644 index a166f0e..0000000 --- a/Manatee.Json.Performance/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Manatee.Json.Performance")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("GameStop, Inc.")] -[assembly: AssemblyProduct("Manatee.Json.Performance")] -[assembly: AssemblyCopyright("Copyright © GameStop, Inc. 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("de798abf-79b3-4295-9a1a-d18b3894e8ef")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Manatee.Json.Tests.Console/Manatee.Json.Tests.Console.csproj b/Manatee.Json.Tests.Console/Manatee.Json.Tests.Console.csproj new file mode 100644 index 0000000..a2e2743 --- /dev/null +++ b/Manatee.Json.Tests.Console/Manatee.Json.Tests.Console.csproj @@ -0,0 +1,12 @@ + + + + Exe + netcoreapp1.1 + + + + + + + \ No newline at end of file diff --git a/Manatee.Json.Tests.Console/Program.cs b/Manatee.Json.Tests.Console/Program.cs new file mode 100644 index 0000000..33af0af --- /dev/null +++ b/Manatee.Json.Tests.Console/Program.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.CompilerServices; +using Manatee.Json.Serialization; + +//[assembly:InternalsVisibleTo("Manatee.Json.DynamicTypes")] + +namespace Manatee.Json.Tests.Console +{ + class Program + { + static void Main(string[] args) + { + var json = new JsonObject + { + ["test1"] = 1, + ["test2"] = "hello" + }; + var serializer = new JsonSerializer(); + var obj = serializer.Deserialize(json); + + System.Console.WriteLine(obj.Test1); + System.Console.WriteLine(obj.Test2); + + System.Console.ReadLine(); + } + } + + internal interface ITest + { + [JsonMapTo("test1")] + int Test1 { get; set; } + [JsonMapTo("test2")] + string Test2 { get; set; } + + event EventHandler SomethingHappened; + + void Action(object withParameter); + int Function(string withParameter); + } +} \ No newline at end of file diff --git a/Manatee.Json.Performance/Associate.cs b/Manatee.Json.Tests.Performance/Associate.cs similarity index 92% rename from Manatee.Json.Performance/Associate.cs rename to Manatee.Json.Tests.Performance/Associate.cs index 6787942..c0639f5 100644 --- a/Manatee.Json.Performance/Associate.cs +++ b/Manatee.Json.Tests.Performance/Associate.cs @@ -1,48 +1,48 @@ -using Manatee.Json.Serialization; - -namespace Manatee.Json.Performance -{ - public class Associate - { - public string Id { get; set; } - - public string FamilyName { get; set; } - - public string GivenName { get; set; } - - public override string ToString() - { - return string.Format("{0} - {1} {2}", Id, GivenName, FamilyName); - } - } - - public class SerializableAssociate : IJsonSerializable - { - public string Id { get; set; } - - public string FamilyName { get; set; } - - public string GivenName { get; set; } - - public void FromJson(JsonValue json, JsonSerializer serializer) - { - Id = json.Object["id"].String; - FamilyName = json.Object["familyName"].String; - GivenName = json.Object["givenName"].String; - } - public JsonValue ToJson(JsonSerializer serializer) - { - var obj = new JsonObject - { - {"id", Id}, - {"familyName", FamilyName}, - {"givenName", GivenName}, - }; - return obj; - } - public override string ToString() - { - return string.Format("{0} - {1} {2}", Id, GivenName, FamilyName); - } - } -} +using Manatee.Json.Serialization; + +namespace Manatee.Json.Tests.Performance +{ + public class Associate + { + public string Id { get; set; } + + public string FamilyName { get; set; } + + public string GivenName { get; set; } + + public override string ToString() + { + return string.Format("{0} - {1} {2}", Id, GivenName, FamilyName); + } + } + + public class SerializableAssociate : IJsonSerializable + { + public string Id { get; set; } + + public string FamilyName { get; set; } + + public string GivenName { get; set; } + + public void FromJson(JsonValue json, JsonSerializer serializer) + { + Id = json.Object["id"].String; + FamilyName = json.Object["familyName"].String; + GivenName = json.Object["givenName"].String; + } + public JsonValue ToJson(JsonSerializer serializer) + { + var obj = new JsonObject + { + {"id", Id}, + {"familyName", FamilyName}, + {"givenName", GivenName}, + }; + return obj; + } + public override string ToString() + { + return string.Format("{0} - {1} {2}", Id, GivenName, FamilyName); + } + } +} diff --git a/Manatee.Json.Performance/Associates.json b/Manatee.Json.Tests.Performance/Associates.json similarity index 93% rename from Manatee.Json.Performance/Associates.json rename to Manatee.Json.Tests.Performance/Associates.json index 4edf3c4..13e9f28 100644 --- a/Manatee.Json.Performance/Associates.json +++ b/Manatee.Json.Tests.Performance/Associates.json @@ -1,43 +1,43 @@ -[ - { - "id": "123456", - "familyName": "User", - "givenName": "POS" - }, - { - "id": "234567", - "familyName": "MUNIZ", - "givenName": "D" - - }, - { - "id": "345678", - "familyName": "Medina", - "givenName": "John" - }, - { - "id": "456789", - "familyName": "Trott", - "givenName": "Stephanie" - }, - { - "id": "987654", - "familyName": "Gutierrez", - "givenName": "Adrian" - }, - { - "id": "876543", - "familyName": "Himmelheber", - "givenName": "Devin" - }, - { - "id": "765432", - "familyName": "Burriss", - "givenName": "Charles" - }, - { - "id": "654321", - "familyName": "Williams", - "givenName": "Nic" - } +[ + { + "id": "123456", + "familyName": "User", + "givenName": "POS" + }, + { + "id": "234567", + "familyName": "MUNIZ", + "givenName": "D" + + }, + { + "id": "345678", + "familyName": "Medina", + "givenName": "John" + }, + { + "id": "456789", + "familyName": "Trott", + "givenName": "Stephanie" + }, + { + "id": "987654", + "familyName": "Gutierrez", + "givenName": "Adrian" + }, + { + "id": "876543", + "familyName": "Himmelheber", + "givenName": "Devin" + }, + { + "id": "765432", + "familyName": "Burriss", + "givenName": "Charles" + }, + { + "id": "654321", + "familyName": "Williams", + "givenName": "Nic" + } ] \ No newline at end of file diff --git a/Manatee.Json.Performance/DeserializeTest.cs b/Manatee.Json.Tests.Performance/DeserializeTest.cs similarity index 96% rename from Manatee.Json.Performance/DeserializeTest.cs rename to Manatee.Json.Tests.Performance/DeserializeTest.cs index df62f78..f615622 100644 --- a/Manatee.Json.Performance/DeserializeTest.cs +++ b/Manatee.Json.Tests.Performance/DeserializeTest.cs @@ -1,138 +1,137 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using Manatee.Json.Serialization; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json; -using JsonSerializer = Manatee.Json.Serialization.JsonSerializer; - -namespace Manatee.Json.Performance -{ - [TestClass] - [DeploymentItem("Associates.json")] - public class DeserializeTest - { - [TestMethod] - public void Performance_FullAutoSerialize_Single() - { - Console.WriteLine("Time To Beat: 00:00:00.0280016"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - var start = DateTime.Now; - var json = JsonValue.Parse(content); - var obj = serializer.Deserialize>(json); - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - start = DateTime.Now; - obj = JsonConvert.DeserializeObject>(content); - end = DateTime.Now; - Console.WriteLine("NewtonSoft: {0}", end - start); - } - [TestMethod] - public void Performance_FullAutoSerialize_10000() - { - Console.WriteLine("Time To Beat: 00:00:01.6560947"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - IEnumerable obj; - var start = DateTime.Now; - for (int i = 0; i < 10000; i++) - { - var json = JsonValue.Parse(content); - obj = serializer.Deserialize>(json); - } - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - start = DateTime.Now; - for (int i = 0; i < 10000; i++) - { - obj = JsonConvert.DeserializeObject>(content); - } - end = DateTime.Now; - Console.WriteLine("NewtonSoft: {0}", end - start); - } - [TestMethod] - public void Performance_FullIJsonSerialize_Single() - { - Console.WriteLine("Time To Beat: 00:00:00.0230013"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - var start = DateTime.Now; - var json = JsonValue.Parse(content); - var obj = serializer.Deserialize>(json); - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - foreach (var serializableAssociate in obj) - { - Console.WriteLine("\t{0}", serializableAssociate); - } - start = DateTime.Now; - var obj2 = JsonConvert.DeserializeObject>(content); - end = DateTime.Now; - Console.WriteLine("NewtonSoft: {0}", end - start); - foreach (var serializableAssociate in obj2) - { - Console.WriteLine("\t{0}", serializableAssociate); - } - } - [TestMethod] - public void Performance_FullIJsonSerialize_10000() - { - Console.WriteLine("Time To Beat: 00:00:00.6080608"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - IEnumerable obj; - var start = DateTime.Now; - for (int i = 0; i < 10000; i++) - { - var json = JsonValue.Parse(content); - obj = serializer.Deserialize>(json); - } - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - start = DateTime.Now; - for (int i = 0; i < 10000; i++) - { - obj = JsonConvert.DeserializeObject>(content); - } - end = DateTime.Now; - Console.WriteLine("NewtonSoft: {0}", end - start); - } - [TestMethod] - public void Performance_IJsonSerializeOnly_Single() - { - Console.WriteLine("Time To Beat: 00:00:00.0120012"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - IEnumerable obj; - var json = JsonValue.Parse(content); - var start = DateTime.Now; - obj = serializer.Deserialize>(json); - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - } - [TestMethod] - public void Performance_IJsonSerializeOnly_10000() - { - Console.WriteLine("Time To Beat: 00:00:00.2130213"); - var content = File.ReadAllText("Associates.json"); - var serializer = new JsonSerializer(); - JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); - IEnumerable obj; - var json = JsonValue.Parse(content); - var start = DateTime.Now; - for (int i = 0; i < 10000; i++) - { - obj = serializer.Deserialize>(json); - } - var end = DateTime.Now; - Console.WriteLine("Manatee: {0}", end - start); - } - } -} +using System; +using System.Collections.Generic; +using System.IO; +using Manatee.Json.Serialization; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Newtonsoft.Json; +using JsonSerializer = Manatee.Json.Serialization.JsonSerializer; + +namespace Manatee.Json.Tests.Performance +{ + [TestClass] + [DeploymentItem("Associates.json")] + public class DeserializeTest + { + [TestMethod] + public void Performance_FullAutoSerialize_Single() + { + Console.WriteLine("Time To Beat: 00:00:00.0280016"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + var start = DateTime.Now; + var json = JsonValue.Parse(content); + var obj = serializer.Deserialize>(json); + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + start = DateTime.Now; + obj = JsonConvert.DeserializeObject>(content); + end = DateTime.Now; + Console.WriteLine("NewtonSoft: {0}", end - start); + } + [TestMethod] + public void Performance_FullAutoSerialize_10000() + { + Console.WriteLine("Time To Beat: 00:00:01.6560947"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + IEnumerable obj; + var start = DateTime.Now; + for (int i = 0; i < 10000; i++) + { + var json = JsonValue.Parse(content); + obj = serializer.Deserialize>(json); + } + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + start = DateTime.Now; + for (int i = 0; i < 10000; i++) + { + obj = JsonConvert.DeserializeObject>(content); + } + end = DateTime.Now; + Console.WriteLine("NewtonSoft: {0}", end - start); + } + [TestMethod] + public void Performance_FullIJsonSerialize_Single() + { + Console.WriteLine("Time To Beat: 00:00:00.0230013"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + var start = DateTime.Now; + var json = JsonValue.Parse(content); + var obj = serializer.Deserialize>(json); + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + foreach (var serializableAssociate in obj) + { + Console.WriteLine("\t{0}", serializableAssociate); + } + start = DateTime.Now; + var obj2 = JsonConvert.DeserializeObject>(content); + end = DateTime.Now; + Console.WriteLine("NewtonSoft: {0}", end - start); + foreach (var serializableAssociate in obj2) + { + Console.WriteLine("\t{0}", serializableAssociate); + } + } + [TestMethod] + public void Performance_FullIJsonSerialize_10000() + { + Console.WriteLine("Time To Beat: 00:00:00.6080608"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + IEnumerable obj; + var start = DateTime.Now; + for (int i = 0; i < 10000; i++) + { + var json = JsonValue.Parse(content); + obj = serializer.Deserialize>(json); + } + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + start = DateTime.Now; + for (int i = 0; i < 10000; i++) + { + obj = JsonConvert.DeserializeObject>(content); + } + end = DateTime.Now; + Console.WriteLine("NewtonSoft: {0}", end - start); + } + [TestMethod] + public void Performance_IJsonSerializeOnly_Single() + { + Console.WriteLine("Time To Beat: 00:00:00.0120012"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + IEnumerable obj; + var json = JsonValue.Parse(content); + var start = DateTime.Now; + obj = serializer.Deserialize>(json); + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + } + [TestMethod] + public void Performance_IJsonSerializeOnly_10000() + { + Console.WriteLine("Time To Beat: 00:00:00.2130213"); + var content = File.ReadAllText("Associates.json"); + var serializer = new JsonSerializer(); + JsonSerializationAbstractionMap.MapGeneric(typeof(IEnumerable<>), typeof(List<>)); + IEnumerable obj; + var json = JsonValue.Parse(content); + var start = DateTime.Now; + for (int i = 0; i < 10000; i++) + { + obj = serializer.Deserialize>(json); + } + var end = DateTime.Now; + Console.WriteLine("Manatee: {0}", end - start); + } + } +} diff --git a/Manatee.Json.Tests.Performance/Manatee.Json.Tests.Performance.csproj b/Manatee.Json.Tests.Performance/Manatee.Json.Tests.Performance.csproj new file mode 100644 index 0000000..2b09692 --- /dev/null +++ b/Manatee.Json.Tests.Performance/Manatee.Json.Tests.Performance.csproj @@ -0,0 +1,81 @@ + + + + + Debug + AnyCPU + {36A1A51A-B8AF-4492-828A-73390286D2F4} + Library + Properties + Manatee.Json.Tests.Performance + Manatee.Json.Tests.Performance + v4.6 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 15.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages + False + UnitTest + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\MSTest.TestFramework.1.1.11\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll + + + ..\packages\MSTest.TestFramework.1.1.11\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll + + + ..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll + + + + + + + + + + + + + Always + + + + + + {7548217b-8c18-4ca5-a248-59889ef93cf5} + Manatee.Json + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/Manatee.Json.Performance/ParseTest.cs b/Manatee.Json.Tests.Performance/ParseTest.cs similarity index 92% rename from Manatee.Json.Performance/ParseTest.cs rename to Manatee.Json.Tests.Performance/ParseTest.cs index bf0cf8e..a307f05 100644 --- a/Manatee.Json.Performance/ParseTest.cs +++ b/Manatee.Json.Tests.Performance/ParseTest.cs @@ -1,38 +1,38 @@ -using System; -using System.IO; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace Manatee.Json.Performance -{ - [TestClass] - [DeploymentItem("Associates.json")] - public class ParseTest - { - [TestMethod] - public void Performance_Parse_Single() - { - Console.WriteLine("Time To Beat: 00:00:00.0110006"); - var content = File.ReadAllText("Associates.json"); - var start = DateTime.Now; - var json = JsonValue.Parse(content); - var end = DateTime.Now; - Console.WriteLine(json); - Console.WriteLine(end - start); - } - [TestMethod] - public void Performance_Parse_10000() - { - Console.WriteLine("Time To Beat: 00:00:00.3410196"); - var content = File.ReadAllText("Associates.json"); - var start = DateTime.Now; - JsonValue json = null; - for (int i = 0; i < 10000; i++) - { - json = JsonValue.Parse(content); - } - var end = DateTime.Now; - Console.WriteLine(json); - Console.WriteLine(end - start); - } - } +using System; +using System.IO; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Manatee.Json.Tests.Performance +{ + [TestClass] + [DeploymentItem("Associates.json")] + public class ParseTest + { + [TestMethod] + public void Performance_Parse_Single() + { + Console.WriteLine("Time To Beat: 00:00:00.0110006"); + var content = File.ReadAllText("Associates.json"); + var start = DateTime.Now; + var json = JsonValue.Parse(content); + var end = DateTime.Now; + Console.WriteLine(json); + Console.WriteLine(end - start); + } + [TestMethod] + public void Performance_Parse_10000() + { + Console.WriteLine("Time To Beat: 00:00:00.3410196"); + var content = File.ReadAllText("Associates.json"); + var start = DateTime.Now; + JsonValue json = null; + for (int i = 0; i < 10000; i++) + { + json = JsonValue.Parse(content); + } + var end = DateTime.Now; + Console.WriteLine(json); + Console.WriteLine(end - start); + } + } } \ No newline at end of file diff --git a/Manatee.Json.Tests.Performance/Properties/AssemblyInfo.cs b/Manatee.Json.Tests.Performance/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..a2366bc --- /dev/null +++ b/Manatee.Json.Tests.Performance/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Manatee.Json.Tests.Performance")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Manatee.Json.Tests.Performance")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +[assembly: ComVisible(false)] + +[assembly: Guid("36a1a51a-b8af-4492-828a-73390286d2f4")] + +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Manatee.Json.Tests.Performance/packages.config b/Manatee.Json.Tests.Performance/packages.config new file mode 100644 index 0000000..4d73a3f --- /dev/null +++ b/Manatee.Json.Tests.Performance/packages.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Manatee.Json.Tests/LinqExtensionsTest.cs b/Manatee.Json.Tests/LinqExtensionsTest.cs index 37d7560..a4611c8 100644 --- a/Manatee.Json.Tests/LinqExtensionsTest.cs +++ b/Manatee.Json.Tests/LinqExtensionsTest.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Manatee.Json.Serialization; using Manatee.Json.Tests.Test_References; @@ -172,13 +173,13 @@ public void FromJson_SerializableArray_ReturnsArray() Assert.IsTrue(expected.SequenceEqual(actual)); } [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] public void FromJson_NullSerializableArray_ReturnsNull() { var serializer = new JsonSerializer(); var json = (JsonArray)null; var expected = (IEnumerable)null; - var actual = json.FromJson(serializer); - Assert.AreEqual(expected, actual); + var actual = json.FromJson(serializer).ToList(); } [TestMethod] public void FromJson_SerializableObject_ReturnsObject() diff --git a/Manatee.Json.Tests/Manatee.Json.Tests.csproj b/Manatee.Json.Tests/Manatee.Json.Tests.csproj index df73651..ebe1a67 100644 --- a/Manatee.Json.Tests/Manatee.Json.Tests.csproj +++ b/Manatee.Json.Tests/Manatee.Json.Tests.csproj @@ -11,7 +11,7 @@ Properties Manatee.Json.Tests Manatee.Json.Tests - v4.5 + v4.6 512 {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} @@ -52,6 +52,7 @@ False + 3.5 @@ -59,8 +60,6 @@ - - @@ -175,9 +174,9 @@ - - {6adf0bcf-4e46-4605-a784-51ea6dac81c7} - Manatee.Json-4.5 + + {7548217b-8c18-4ca5-a248-59889ef93cf5} + Manatee.Json diff --git a/Manatee.Json.Tests/Manatee.Json.Tests.csproj.user b/Manatee.Json.Tests/Manatee.Json.Tests.csproj.user deleted file mode 100644 index 76fe5a5..0000000 --- a/Manatee.Json.Tests/Manatee.Json.Tests.csproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - - ProjectFiles - - \ No newline at end of file diff --git a/Manatee.Json.Tests/Serialization/Internal/TypeGeneratorTest.cs b/Manatee.Json.Tests/Serialization/Internal/TypeGeneratorTest.cs index b99b7a4..31256a2 100644 --- a/Manatee.Json.Tests/Serialization/Internal/TypeGeneratorTest.cs +++ b/Manatee.Json.Tests/Serialization/Internal/TypeGeneratorTest.cs @@ -3,8 +3,6 @@ using Manatee.Json.Tests.Test_References; using Microsoft.VisualStudio.TestTools.UnitTesting; -#if !IOS - namespace Manatee.Json.Tests.Serialization.Internal { [TestClass] @@ -58,5 +56,3 @@ public void CacheTypes_Success() } } } - -#endif \ No newline at end of file diff --git a/Manatee.Json.Tests/Serialization/JsonSerializerTest.cs b/Manatee.Json.Tests/Serialization/JsonSerializerTest.cs index ada198c..7cb82d3 100644 --- a/Manatee.Json.Tests/Serialization/JsonSerializerTest.cs +++ b/Manatee.Json.Tests/Serialization/JsonSerializerTest.cs @@ -291,9 +291,6 @@ public void AbstractClass_Successful() Assert.AreEqual(expected, actual); } [TestMethod] -#if IOS - [Ignore] -#endif public void Interface_Successful() { var serializer = new JsonSerializer(); @@ -338,7 +335,7 @@ public void IJsonSerializable_Successful() Assert.AreEqual(expected, actual); } [TestMethod] - public void Array_Successfull() + public void Array_Successful() { var serializer = new JsonSerializer(); var list = new[] {4, 3, 5, 6}; @@ -347,7 +344,7 @@ public void Array_Successfull() Assert.AreEqual(expected, actual); } [TestMethod] - public void List_Successfull() + public void List_Successful() { var serializer = new JsonSerializer(); var list = new List {4, 3, 5, 6}; @@ -356,7 +353,7 @@ public void List_Successfull() Assert.AreEqual(expected, actual); } [TestMethod] - public void IEnumerable_Successfull() + public void IEnumerable_Successful() { var serializer = new JsonSerializer(); JsonSerializationAbstractionMap.MapGeneric(typeof (IEnumerable<>), typeof (List<>)); @@ -381,7 +378,7 @@ public void Dictionary_Successful() Assert.AreEqual(expected, actual); } [TestMethod] - public void Queue_Successfull() + public void Queue_Successful() { var serializer = new JsonSerializer(); var queue = new Queue(); @@ -394,7 +391,7 @@ public void Queue_Successfull() Assert.AreEqual(expected, actual); } [TestMethod] - public void Stack_Successfull() + public void Stack_Successful() { var serializer = new JsonSerializer(); var stack = new Stack(); @@ -407,7 +404,7 @@ public void Stack_Successfull() Assert.AreEqual(expected, actual); } [TestMethod] - public void SerializeType_Successfull() + public void SerializeType_Successful() { var serializer = new JsonSerializer(); ObjectWithBasicProps.StaticStringProp = "staticStringValue"; diff --git a/Manatee.Json.Tests/Test References/ObjectWithBasicProps.cs b/Manatee.Json.Tests/Test References/ObjectWithBasicProps.cs index a2bb730..c591e8d 100644 --- a/Manatee.Json.Tests/Test References/ObjectWithBasicProps.cs +++ b/Manatee.Json.Tests/Test References/ObjectWithBasicProps.cs @@ -1,5 +1,5 @@ using System; -using System.ComponentModel; +using System.ComponentModel.DataAnnotations; using Manatee.Json.Serialization; namespace Manatee.Json.Tests.Test_References @@ -90,7 +90,7 @@ public enum TestEnum { None, BasicEnumValue, - [Description("enum_value_with_description")] + [Display(Description = "enum_value_with_description")] EnumValueWithDescription } @@ -99,7 +99,7 @@ public enum FlagsEnum { None = 0, BasicEnumValue = 1, - [Description("enum_value_with_description")] + [Display(Description = "enum_value_with_description")] EnumValueWithDescription = 2 } // ReSharper restore UnusedAutoPropertyAccessor.Local diff --git a/Manatee.Json.sln b/Manatee.Json.sln index f51115f..228257e 100644 --- a/Manatee.Json.sln +++ b/Manatee.Json.sln @@ -1,10 +1,8 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 +# Visual Studio 15 +VisualStudioVersion = 15.0.26430.13 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json-4.5", "Manatee.Json\Manatee.Json-4.5.csproj", "{6ADF0BCF-4E46-4605-A784-51EA6DAC81C7}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8C148909-BDAD-45A5-9BFA-63DBD47290B9}" ProjectSection(SolutionItems) = preProject LICENSE-2.0.txt = LICENSE-2.0.txt @@ -16,13 +14,9 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json.Tests", "Manat EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{6E84846A-D11A-4B3F-9588-C815FB0A22C5}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json-3.5", "Manatee.Json\Manatee.Json-3.5.csproj", "{FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json-4.0", "Manatee.Json\Manatee.Json-4.0.csproj", "{67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json-Portable", "Manatee.Json\Manatee.Json-Portable.csproj", "{B0A832B8-06B7-4494-8416-FABE755F621F}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Manatee.Json", "Manatee.Json\Manatee.Json.csproj", "{7548217B-8C18-4CA5-A248-59889EF93CF5}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Manatee.Json-Core", "Manatee.Json\Manatee.Json-Core.xproj", "{A83D9791-01A7-4031-886E-995B7A1320D1}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Manatee.Json.Tests.Console", "Manatee.Json.Tests.Console\Manatee.Json.Tests.Console.csproj", "{861C40FB-5D2E-4051-A1F0-D9B9C5D74794}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -30,35 +24,24 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7}.Release|Any CPU.Build.0 = Release|Any CPU {E74B7538-5E17-43C7-925B-33784945312E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E74B7538-5E17-43C7-925B-33784945312E}.Debug|Any CPU.Build.0 = Debug|Any CPU {E74B7538-5E17-43C7-925B-33784945312E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA}.Release|Any CPU.Build.0 = Release|Any CPU - {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E}.Release|Any CPU.Build.0 = Release|Any CPU - {B0A832B8-06B7-4494-8416-FABE755F621F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B0A832B8-06B7-4494-8416-FABE755F621F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B0A832B8-06B7-4494-8416-FABE755F621F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B0A832B8-06B7-4494-8416-FABE755F621F}.Release|Any CPU.Build.0 = Release|Any CPU - {A83D9791-01A7-4031-886E-995B7A1320D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A83D9791-01A7-4031-886E-995B7A1320D1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A83D9791-01A7-4031-886E-995B7A1320D1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A83D9791-01A7-4031-886E-995B7A1320D1}.Release|Any CPU.Build.0 = Release|Any CPU + {7548217B-8C18-4CA5-A248-59889EF93CF5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7548217B-8C18-4CA5-A248-59889EF93CF5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7548217B-8C18-4CA5-A248-59889EF93CF5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7548217B-8C18-4CA5-A248-59889EF93CF5}.Release|Any CPU.Build.0 = Release|Any CPU + {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Debug|Any CPU.Build.0 = Debug|Any CPU + {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Release|Any CPU.ActiveCfg = Release|Any CPU + {861C40FB-5D2E-4051-A1F0-D9B9C5D74794}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {E74B7538-5E17-43C7-925B-33784945312E} = {6E84846A-D11A-4B3F-9588-C815FB0A22C5} + {861C40FB-5D2E-4051-A1F0-D9B9C5D74794} = {6E84846A-D11A-4B3F-9588-C815FB0A22C5} EndGlobalSection GlobalSection(TestCaseManagementSettings) = postSolution CategoryFile = Json.vsmdi diff --git a/Manatee.Json.sln.DotSettings b/Manatee.Json.sln.DotSettings index 1237c76..18d2ca7 100644 --- a/Manatee.Json.sln.DotSettings +++ b/Manatee.Json.sln.DotSettings @@ -24,4 +24,4 @@ True True True - <data><IncludeFilters /><ExcludeFilters><Filter ModuleMask="Manatee.Json" ModuleVersionMask="*" ClassMask="Manatee.Json.Path.JsonPathRoot" FunctionMask="*" IsEnabled="True" /></ExcludeFilters></data> \ No newline at end of file + <data><IncludeFilters /><ExcludeFilters><Filter ModuleMask="Manatee.Json" ModuleVersionMask="*" ClassMask="Manatee.Json.Path.JsonPathRoot" FunctionMask="*" IsEnabled="True" /><Filter ModuleMask="Manatee.Json.Tests" ModuleVersionMask="*" ClassMask="*" FunctionMask="*" IsEnabled="True" /></ExcludeFilters></data> \ No newline at end of file diff --git a/Manatee.Json.sln.DotSettings.user b/Manatee.Json.sln.DotSettings.user index 900e72b..db3369a 100644 --- a/Manatee.Json.sln.DotSettings.user +++ b/Manatee.Json.sln.DotSettings.user @@ -1,5 +1,9 @@  - SOLUTION + <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /> + + + + 0 @@ -9,10 +13,10 @@ True - (Doc Ln 24 Col 13) + (Doc Ln 47 Col 13) 6ADF0BCF-4E46-4605-A784-51EA6DAC81C7/d:Path/d:Expressions/f:IsLessThanExpression.cs NumberedBookmarkManager True - (Doc Ln 186 Col 20) + (Doc Ln 210 Col 20) 6ADF0BCF-4E46-4605-A784-51EA6DAC81C7/d:Serialization/d:Internal/d:Serializers/f:AutoSerializer.cs NumberedBookmarkManager \ No newline at end of file diff --git a/Manatee.Json/DescriptionAttribute.cs b/Manatee.Json/DescriptionAttribute.cs deleted file mode 100644 index efd0ce0..0000000 --- a/Manatee.Json/DescriptionAttribute.cs +++ /dev/null @@ -1,26 +0,0 @@ -#if IOS || CORE -using System; - -namespace Manatee.Json -{ - /// - /// - /// - [AttributeUsage(AttributeTargets.All)] - public class DescriptionAttribute : Attribute - { - /// - /// Gets the description. - /// - public string Description { get; } - - /// - /// Creates a new instance of the class. - /// - public DescriptionAttribute(string description) - { - Description = description; - } - } -} -#endif diff --git a/Manatee.Json/Internal/CompatibilityExtensions.cs b/Manatee.Json/Internal/CompatibilityExtensions.cs deleted file mode 100644 index d167cb5..0000000 --- a/Manatee.Json/Internal/CompatibilityExtensions.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Manatee.Json.Internal -{ - internal static class CompatibilityExtensions - { - //[MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsNullOrWhiteSpace(this string value) - { -#if NET35 - return string.IsNullOrEmpty(value) || string.IsNullOrEmpty(value.Trim()); -#else - return string.IsNullOrWhiteSpace(value); -#endif - } - //[MethodImpl(MethodImplOptions.AggressiveInlining)] - public static string Join(this IEnumerable segments, string separator) - { -#if NET35 - return string.Join(separator, segments.Select(s => s.ToString()).ToArray()); -#else - return string.Join(separator, segments); -#endif - } -#if IOS || CORE - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static TypeInfo TypeInfo(this Type type) - { - return type.GetTypeInfo(); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Type[] GetTypeArguments(this Type type) - { - return type.GetTypeInfo().GenericTypeArguments; - } -#else - //[MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Type TypeInfo(this Type type) - { - return type; - } - //[MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Type[] GetTypeArguments(this Type type) - { - return type.GetGenericArguments(); - } -#endif -#if IOS - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool Any(this string value, Func predicate) - { - return value.ToCharArray().Any(predicate); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable TakeWhile(this string value, Func predicate) - { - return value.ToCharArray().TakeWhile(predicate); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool Contains(this string value, char c) - { - return value.ToCharArray().Contains(c); - } - public static IEnumerable GetInterfaces(this TypeInfo type) - { - return type.ImplementedInterfaces; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsAssignableFrom(this Type derivedType, Type baseType) - { - return derivedType.TypeInfo().IsAssignableFrom(baseType.TypeInfo()); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MethodInfo GetMethod(this Type type, string name) - { - return type.TypeInfo().GetDeclaredMethod(name); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MemberInfo[] GetMember(this TypeInfo typeInfo, string name) - { - return typeInfo.DeclaredMembers.Where(m => m.Name == name).ToArray(); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MethodInfo GetSetMethod(this PropertyInfo property) - { - return property.SetMethod; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MethodInfo GetGetMethod(this PropertyInfo property) - { - return property.GetMethod; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static IEnumerable GetTypes(this Assembly assembly) - { - return assembly.ExportedTypes; - } -#endif -#if CORE - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsAssignableFrom(this Type derivedType, Type baseType) - { - return derivedType.TypeInfo().IsAssignableFrom(baseType); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MethodInfo GetMethod(this Type type, string name, BindingFlags flags = BindingFlags.Default) - { - return type.TypeInfo().GetMethod(name, flags); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static MethodInfo GetMethod(this Type type, string name, Type[] typeParams) - { - return type.TypeInfo().GetMethod(name, typeParams); - } -#endif - } -} diff --git a/Manatee.Json/Internal/GeneralExtensions.cs b/Manatee.Json/Internal/GeneralExtensions.cs index f7fe727..5a9f43c 100644 --- a/Manatee.Json/Internal/GeneralExtensions.cs +++ b/Manatee.Json/Internal/GeneralExtensions.cs @@ -1,218 +1,30 @@ using System; using System.Collections.Generic; -using System.Globalization; -using System.IO; using System.Linq; -using System.Reflection; -using Manatee.Json.Internal; +using System.Runtime.CompilerServices; namespace Manatee.Json.Internal { internal static class GeneralExtensions { - private static readonly IEnumerable AvailableChars = Enumerable.Range(ushort.MinValue, ushort.MaxValue) - .Select(n => (char)n) - .Where(c => !char.IsControl(c)); - + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool In(this T value, params T[] collection) { return collection.Contains(value); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInt(this double value) { return Math.Ceiling(value) == Math.Floor(value); } - public static IEnumerable NotNull(this IEnumerable items) - where T : class - { - return items.Where(i => i != null); - } - public static string EvaluateEscapeSequences(this string source, out string result) - { - var i = 0; - while (i < source.Length) - { - var length = 1; - if (source[i] == '\\') - switch (source[i + 1]) - { - case '"': - case '/': - case '\\': - source = source.Remove(i, 1); - break; - case 'b': - source = source.Substring(0, i) + '\b' + source.Substring(i + length + 1); - break; - case 'f': - source = source.Substring(0, i) + '\f' + source.Substring(i + length + 1); - break; - case 'n': - source = source.Substring(0, i) + '\n' + source.Substring(i + length + 1); - break; - case 'r': - source = source.Substring(0, i) + '\r' + source.Substring(i + length + 1); - break; - case 't': - source = source.Substring(0, i) + '\t' + source.Substring(i + length + 1); - break; - case 'u': - length = 6; - var hex = int.Parse(source.Substring(i + 2, 4), NumberStyles.HexNumber); - if (source.Substring(i + 6, 2) == "\\u") - { - var hex2 = int.Parse(source.Substring(i + 8, 4), NumberStyles.HexNumber); - hex = (hex - 0xD800)*0x400 + (hex2 - 0xDC00)%0x400 + 0x10000; - length += 6; - } - source = source.Substring(0, i) + char.ConvertFromUtf32(hex) + source.Substring(i + length); - length = 2; // unicode pairs are 2 chars in .Net strings. - break; - default: - result = source; - return $"Invalid escape sequence: '\\{source[i + 1]}'."; - } - i += length; - } - result = source; - return null; - } - public static string InsertEscapeSequences(this string source) - { - var index = 0; - while (index < source.Length) - { - var count = 0; - string replace = null; - switch (source[index]) - { - case '"': - case '\\': - source = source.Insert(index, "\\"); - index++; - break; - case '\b': - count = 1; - replace = "\\b"; - break; - case '\f': - count = 1; - replace = "\\f"; - break; - case '\n': - count = 1; - replace = "\\n"; - break; - case '\r': - count = 1; - replace = "\\r"; - break; - case '\t': - count = 1; - replace = "\\t"; - break; - default: - if (!AvailableChars.Contains(source[index])) - { - var hex = Convert.ToInt16(source[index]).ToString("X4"); - source = source.Substring(0, index) + "\\u" + hex + source.Substring(index + 1); - index += 5; - } - break; - } - if (replace != null) - { - source = Replace(source, index, count, replace); - index++; - } - index++; - } - return source; - } - private static string Replace(string source, int index, int count, string content) - { - // I've checked both of these methods with ILSpy. They occur in external methods, so - // we're not going to do much better than this. - return source.Remove(index, count).Insert(index, content); - } - public static string SkipWhiteSpace(this string source, ref int index, int length, out char ch) - { - if (index >= length) - { - ch = default(char); - return "Unexpected end of input."; - } - var c = source[index]; - while (index < length) - { - if (!char.IsWhiteSpace(c)) break; - index++; - if (index >= length) - { - ch = default(char); - return "Unexpected end of input."; - } - c = source[index]; - } - if (index >= length) - { - ch = default(char); - return "Unexpected end of input."; - } - ch = c; - return null; - } - public static string SkipWhiteSpace(this StreamReader stream, out char ch) - { - if (stream.EndOfStream) - { - ch = default(char); - return "Unexpected end of input."; - } - ch = (char) stream.Peek(); - while (!stream.EndOfStream) - { - if (!char.IsWhiteSpace(ch)) break; - stream.Read(); - ch = (char) stream.Peek(); - } - if (stream.EndOfStream) - { - ch = default(char); - return "Unexpected end of input."; - } - return null; - } - // Note: These methods assume that if a generic type is passed, the type is open. - public static bool InheritsFrom(this Type tDerived, Type tBase) - { - if (tDerived.IsSubtypeOf(tBase)) return true; - var interfaces = tDerived.TypeInfo().GetInterfaces().Select(i => i.TypeInfo().IsGenericType ? i.GetGenericTypeDefinition() : i); - return interfaces.Contains(tBase); - } - private static bool IsSubtypeOf(this Type tDerived, Type tBase) - { - var currentType = tDerived.TypeInfo().BaseType; - while (currentType != null) - { - if (currentType.TypeInfo().IsGenericType) - currentType = currentType.GetGenericTypeDefinition(); - if (currentType == tBase) return true; - currentType = currentType.TypeInfo().BaseType; - } - return false; - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetCollectionHashCode(this IEnumerable collection) { return collection.Aggregate(0, (current, obj) => unchecked(current * 397) ^ obj.GetHashCode()); } public static int GetCollectionHashCode(this IEnumerable> collection) { -#if IOS || CORE return collection.OrderBy(kvp => kvp.Key, StringComparer.Ordinal) -#else - return collection.OrderBy(kvp => kvp.Key, StringComparer.InvariantCulture) -#endif .Aggregate(0, (current, kvp) => { unchecked @@ -223,27 +35,18 @@ public static int GetCollectionHashCode(this IEnumerable(this IEnumerable a, IEnumerable b) - { - if (a == null && b != null) return false; - if (a != null && b == null) return false; - if (a == null) return true; - - var listA = a.ToList(); - var listB = b.ToList(); - return listA.Count == listB.Count && listA.All(item => listB.Contains(item)); - } public static JsonValue AsJsonValue(this object value) { - if (value is JsonValue) return (JsonValue) value; - if (value is JsonArray) return (JsonArray) value; - if (value is JsonObject) return (JsonObject) value; - if (value is string) return (string) value; + if (value is JsonValue jsonValue) return jsonValue; + if (value is JsonArray jsonArray) return jsonArray; + if (value is JsonObject jsonObject) return jsonObject; + if (value is string s) return s; if (value is bool) return (bool) value; if (value.IsNumber()) return Convert.ToDouble(value); return null; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNumber(this object value) { return value is double || @@ -256,17 +59,5 @@ public static bool IsNumber(this object value) value is long || value is ulong; } - public static Uri GetBase(this Uri uri) - { - Uri previous = uri; - do - { - uri = previous; - previous = uri.GetParentUri(); - } while (uri != previous); - - return uri; - } - } } \ No newline at end of file diff --git a/Manatee.Json/Internal/JsonPathInput.cs b/Manatee.Json/Internal/JsonPathInput.cs deleted file mode 100644 index c52db5a..0000000 --- a/Manatee.Json/Internal/JsonPathInput.cs +++ /dev/null @@ -1,42 +0,0 @@ -/*************************************************************************************** - - Copyright 2016 Greg Dennis - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - File Name: JsonPathInput.cs - Namespace: Manatee.Json.Internal - Class Name: JsonPathInput - Purpose: Enumerates input types for JSON Paths. - -***************************************************************************************/ - -namespace Manatee.Json.Internal -{ - internal enum JsonPathInput - { - Dollar, - Current, - OpenBracket, - CloseBracket, - Period, - Star, - OpenParenth, - Question, - Number, - Letter, - Colon, - Comma, - End - } -} \ No newline at end of file diff --git a/Manatee.Json/Internal/LinqExtensions.cs b/Manatee.Json/Internal/LinqExtensions.cs new file mode 100644 index 0000000..275c64e --- /dev/null +++ b/Manatee.Json/Internal/LinqExtensions.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Manatee.Json.Internal +{ + internal static class LinqExtensions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEnumerable WhereNotNull(this IEnumerable items) + where T : class + { + return items.Where(i => i != null); + } + public static bool ContentsEqual(this IEnumerable a, IEnumerable b) + { + if (a == null && b != null) return false; + if (a != null && b == null) return false; + if (a == null) return true; + + var listA = a.ToList(); + var listB = b.ToList(); + return listA.Count == listB.Count && listA.All(item => listB.Contains(item)); + } + } +} \ No newline at end of file diff --git a/Manatee.Json/Internal/ReflectionExtensions.cs b/Manatee.Json/Internal/ReflectionExtensions.cs new file mode 100644 index 0000000..d8be6db --- /dev/null +++ b/Manatee.Json/Internal/ReflectionExtensions.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Manatee.Json.Internal +{ + internal static class ReflectionExtensions + { + // Note: These methods assume that if a generic type is passed, the type is open. + public static bool InheritsFrom(this Type tDerived, Type tBase) + { + if (tDerived._IsSubtypeOf(tBase)) return true; + var interfaces = tDerived.GetTypeInfo().ImplementedInterfaces.Select(i => IntrospectionExtensions.GetTypeInfo(i).IsGenericType ? i.GetGenericTypeDefinition() : i); + return interfaces.Contains(tBase); + } + private static bool _IsSubtypeOf(this Type tDerived, Type tBase) + { + var currentType = tDerived.GetTypeInfo().BaseType; + while (currentType != null) + { + if (currentType.GetTypeInfo().IsGenericType) + currentType = currentType.GetGenericTypeDefinition(); + if (currentType == tBase) return true; + currentType = currentType.GetTypeInfo().BaseType; + } + return false; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Type[] GetTypeArguments(this Type type) + { + return type.GetTypeInfo().GenericTypeArguments; + } + public static IEnumerable GetAllProperties(this TypeInfo type) + { + var properties = new List(); + while (type != null) + { + properties.AddRange(type.DeclaredProperties); + type = type.BaseType?.GetTypeInfo(); + } + return properties; + } + } +} \ No newline at end of file diff --git a/Manatee.Json/Internal/StringExtensions.cs b/Manatee.Json/Internal/StringExtensions.cs new file mode 100644 index 0000000..005a4be --- /dev/null +++ b/Manatee.Json/Internal/StringExtensions.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; + +namespace Manatee.Json.Internal +{ + internal static class StringExtensions + { + private static readonly IEnumerable AvailableChars = Enumerable.Range(UInt16.MinValue, UInt16.MaxValue) + .Select(n => (char) n) + .Where(c => !Char.IsControl(c)); + + public static string EvaluateEscapeSequences(this string source, out string result) + { + var i = 0; + while (i < source.Length) + { + var length = 1; + if (source[i] == '\\') + switch (source[i + 1]) + { + case '"': + case '/': + case '\\': + source = source.Remove(i, 1); + break; + case 'b': + source = source.Substring(0, i) + '\b' + source.Substring(i + length + 1); + break; + case 'f': + source = source.Substring(0, i) + '\f' + source.Substring(i + length + 1); + break; + case 'n': + source = source.Substring(0, i) + '\n' + source.Substring(i + length + 1); + break; + case 'r': + source = source.Substring(0, i) + '\r' + source.Substring(i + length + 1); + break; + case 't': + source = source.Substring(0, i) + '\t' + source.Substring(i + length + 1); + break; + case 'u': + length = 6; + var hex = Int32.Parse(source.Substring(i + 2, 4), NumberStyles.HexNumber); + if (source.Substring(i + 6, 2) == "\\u") + { + var hex2 = Int32.Parse(source.Substring(i + 8, 4), NumberStyles.HexNumber); + hex = (hex - 0xD800) * 0x400 + (hex2 - 0xDC00) % 0x400 + 0x10000; + length += 6; + } + source = source.Substring(0, i) + Char.ConvertFromUtf32(hex) + source.Substring(i + length); + length = 2; // unicode pairs are 2 chars in .Net strings. + break; + default: + result = source; + return $"Invalid escape sequence: '\\{source[i + 1]}'."; + } + i += length; + } + result = source; + return null; + } + public static string InsertEscapeSequences(this string source) + { + var index = 0; + while (index < source.Length) + { + var count = 0; + string replace = null; + switch (source[index]) + { + case '"': + case '\\': + source = source.Insert(index, "\\"); + index++; + break; + case '\b': + count = 1; + replace = "\\b"; + break; + case '\f': + count = 1; + replace = "\\f"; + break; + case '\n': + count = 1; + replace = "\\n"; + break; + case '\r': + count = 1; + replace = "\\r"; + break; + case '\t': + count = 1; + replace = "\\t"; + break; + default: + if (!Enumerable.Contains(AvailableChars, source[index])) + { + var hex = Convert.ToInt16(source[index]).ToString("X4"); + source = source.Substring(0, index) + "\\u" + hex + source.Substring(index + 1); + index += 5; + } + break; + } + if (replace != null) + { + source = _Replace(source, index, count, replace); + index++; + } + index++; + } + return source; + } + private static string _Replace(string source, int index, int count, string content) + { + // I've checked both of these methods with ILSpy. They occur in external methods, so + // we're not going to do much better than this. + return source.Remove(index, count).Insert(index, content); + } + public static string SkipWhiteSpace(this string source, ref int index, int length, out char ch) + { + if (index >= length) + { + ch = default(char); + return "Unexpected end of input."; + } + var c = source[index]; + while (index < length) + { + if (!Char.IsWhiteSpace(c)) break; + index++; + if (index >= length) + { + ch = default(char); + return "Unexpected end of input."; + } + c = source[index]; + } + if (index >= length) + { + ch = default(char); + return "Unexpected end of input."; + } + ch = c; + return null; + } + public static string SkipWhiteSpace(this StreamReader stream, out char ch) + { + if (stream.EndOfStream) + { + ch = default(char); + return "Unexpected end of input."; + } + ch = (char) stream.Peek(); + while (!stream.EndOfStream) + { + if (!Char.IsWhiteSpace(ch)) break; + stream.Read(); + ch = (char) stream.Peek(); + } + if (stream.EndOfStream) + { + ch = default(char); + return "Unexpected end of input."; + } + return null; + } + } +} \ No newline at end of file diff --git a/Manatee.Json/Internal/XmlNamespaceRegistry.cs b/Manatee.Json/Internal/XmlNamespaceRegistry.cs index 3d5ce79..019234e 100644 --- a/Manatee.Json/Internal/XmlNamespaceRegistry.cs +++ b/Manatee.Json/Internal/XmlNamespaceRegistry.cs @@ -34,8 +34,7 @@ public void UnRegisterElement(XElement element) } public bool ElementDefinesNamespace(XElement element, string space) { - List entry; - return _registry.TryGetValue(element, out entry) && entry.Any(pair => pair.Namespace == space); + return _registry.TryGetValue(element, out List entry) && entry.Any(pair => pair.Namespace == space); } public string GetLabel(XElement element, string space) { @@ -44,8 +43,7 @@ public string GetLabel(XElement element, string space) public void Register(string label, string space) { - Stack entry; - if (!_stack.TryGetValue(label, out entry)) + if (!_stack.TryGetValue(label, out Stack entry)) { entry = new Stack(); _stack.Add(label, entry); @@ -60,8 +58,7 @@ public void Unregister(string label) } public string GetNamespace(string label) { - Stack entry; - if (!_stack.TryGetValue(label, out entry)) return null; + if (!_stack.TryGetValue(label, out Stack entry)) return null; return _stack.TryGetValue(label, out entry) && entry.Count != 0 ? entry.Peek() : null; } } diff --git a/Manatee.Json/JsonArray.cs b/Manatee.Json/JsonArray.cs index 0915766..1f047ca 100644 --- a/Manatee.Json/JsonArray.cs +++ b/Manatee.Json/JsonArray.cs @@ -24,10 +24,7 @@ public class JsonArray : List /// /// public JsonArray(IEnumerable collection) - : base(collection) - { - - } + : base(collection) { } /// /// Creates a string representation of the JSON data. diff --git a/Manatee.Json/JsonObjectExtensions.cs b/Manatee.Json/JsonObjectExtensions.cs index 191b43b..606e7ef 100644 --- a/Manatee.Json/JsonObjectExtensions.cs +++ b/Manatee.Json/JsonObjectExtensions.cs @@ -15,7 +15,7 @@ public static class JsonObjectExtensions /// A or null if the key is not found or is not a public static string TryGetString(this JsonObject obj, string key) { - return (obj == null) ? null : obj.ContainsKey(key) && (obj[key].Type == JsonValueType.String) ? obj[key].String : null; + return obj == null ? null : obj.ContainsKey(key) && obj[key].Type == JsonValueType.String ? obj[key].String : null; } /// /// Returns a or null if the key is not found or is not a double. @@ -25,7 +25,7 @@ public static string TryGetString(this JsonObject obj, string key) /// A or null if the key is not found or is not a public static double? TryGetNumber(this JsonObject obj, string key) { - return (obj == null) ? null : obj.ContainsKey(key) && (obj[key].Type == JsonValueType.Number) ? obj[key].Number : (double?)null; + return obj == null ? null : obj.ContainsKey(key) && obj[key].Type == JsonValueType.Number ? obj[key].Number : (double?)null; } /// /// Returns a or null if the key is not found or is not a . @@ -35,7 +35,7 @@ public static string TryGetString(this JsonObject obj, string key) /// A or null if the key is not found or is not a public static bool? TryGetBoolean(this JsonObject obj, string key) { - return (obj == null) ? null : obj.ContainsKey(key) && (obj[key].Type == JsonValueType.Boolean) ? obj[key].Boolean : (bool?)null; + return obj == null ? null : obj.ContainsKey(key) && obj[key].Type == JsonValueType.Boolean ? obj[key].Boolean : (bool?)null; } /// /// Returns a or null if the key is not found or is not a . @@ -45,7 +45,7 @@ public static string TryGetString(this JsonObject obj, string key) /// A or null if the key is not found or is not a public static JsonArray TryGetArray(this JsonObject obj, string key) { - return (obj == null) ? null : obj.ContainsKey(key) && (obj[key].Type == JsonValueType.Array) ? obj[key].Array : null; + return obj == null ? null : obj.ContainsKey(key) && obj[key].Type == JsonValueType.Array ? obj[key].Array : null; } /// /// Returns a or null if the key is not found or is not a . @@ -55,7 +55,7 @@ public static JsonArray TryGetArray(this JsonObject obj, string key) /// A or null if the key is not found or is not a public static JsonObject TryGetObject(this JsonObject obj, string key) { - return (obj == null) ? null : obj.ContainsKey(key) && (obj[key].Type == JsonValueType.Object) ? obj[key].Object : null; + return obj == null ? null : obj.ContainsKey(key) && obj[key].Type == JsonValueType.Object ? obj[key].Object : null; } } } diff --git a/Manatee.Json/JsonSyntaxException.cs b/Manatee.Json/JsonSyntaxException.cs index 4729be9..e136766 100644 --- a/Manatee.Json/JsonSyntaxException.cs +++ b/Manatee.Json/JsonSyntaxException.cs @@ -7,9 +7,6 @@ namespace Manatee.Json /// /// Thrown when an input string contains a syntax error while parsing a , , or . /// -#if !IOS && !CORE - [Serializable] -#endif public class JsonSyntaxException : Exception { private readonly string _path; @@ -32,10 +29,10 @@ public class JsonSyntaxException : Exception internal JsonSyntaxException(string message, JsonValue value) : base(message) { - _path = BuildPath(value); + _path = _BuildPath(value); } - private static string BuildPath(JsonValue value) + private static string _BuildPath(JsonValue value) { if (value == null) return string.Empty; switch (value.Type) @@ -44,12 +41,12 @@ private static string BuildPath(JsonValue value) if (!value.Object.Any()) return string.Empty; var pair = value.Object.Last(); var key = pair.Key; - return $".{key}{BuildPath(pair.Value)}"; + return $".{key}{_BuildPath(pair.Value)}"; case JsonValueType.Array: if (!value.Array.Any()) return string.Empty; var item = value.Array.Last(); var index = value.Array.Count - 1; - return $"[{index}]{BuildPath(item)}"; + return $"[{index}]{_BuildPath(item)}"; default: return string.Empty; } diff --git a/Manatee.Json/JsonValue.cs b/Manatee.Json/JsonValue.cs index af48c43..f493dff 100644 --- a/Manatee.Json/JsonValue.cs +++ b/Manatee.Json/JsonValue.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics; using System.Globalization; using System.IO; using Manatee.Json.Internal; @@ -326,7 +325,7 @@ public static JsonValue Parse(string source) { if (source == null) throw new ArgumentNullException(nameof(source)); - if (source.IsNullOrWhiteSpace()) + if (string.IsNullOrWhiteSpace(source)) throw new ArgumentException("Source string contains no data."); return JsonParser.Parse(source); } diff --git a/Manatee.Json/JsonValueIncorrectTypeException.cs b/Manatee.Json/JsonValueIncorrectTypeException.cs index d6bf56d..fd57e0f 100644 --- a/Manatee.Json/JsonValueIncorrectTypeException.cs +++ b/Manatee.Json/JsonValueIncorrectTypeException.cs @@ -5,9 +5,6 @@ namespace Manatee.Json /// /// Thrown when a value is accessed via the incorrect type accessor. /// -#if !IOS && !CORE - [Serializable] -#endif public class JsonValueIncorrectTypeException : InvalidOperationException { /// diff --git a/Manatee.Json/LinqExtensions.cs b/Manatee.Json/LinqExtensions.cs index 98c8fd5..89bdf96 100644 --- a/Manatee.Json/LinqExtensions.cs +++ b/Manatee.Json/LinqExtensions.cs @@ -3,8 +3,6 @@ using System.Linq; using Manatee.Json.Serialization; -//using Manatee.Json.Serialization; - namespace Manatee.Json { /// @@ -168,15 +166,14 @@ public static JsonObject ToJson(this IEnumerable> res public static IEnumerable FromJson(this IEnumerable json, JsonSerializer serializer) where T : IJsonSerializable, new() { - if (json == null) return null; - var list = new List(); + if (json == null) throw new ArgumentNullException(nameof(json)); + foreach (var value in json) { T item = new T(); item.FromJson(value, serializer); - list.Add(item); + yield return item; } - return list; } /// /// Deserializes a to its equivalent object. @@ -190,6 +187,7 @@ public static T FromJson(this JsonObject json, JsonSerializer serializer) where T : IJsonSerializable, new() { if (json == null) return default(T); + T obj = new T(); obj.FromJson(json, serializer); return obj; diff --git a/Manatee.Json/Manatee.Json-3.5.csproj b/Manatee.Json/Manatee.Json-3.5.csproj deleted file mode 100644 index 5b5ac0a..0000000 --- a/Manatee.Json/Manatee.Json-3.5.csproj +++ /dev/null @@ -1,310 +0,0 @@ - - - - - Debug - AnyCPU - {FA1616A9-DF70-40E9-B7E8-AAD1D8AC8CAA} - Library - Properties - Manatee.Json - Manatee.Json - v3.5 - 512 - Client - - - true - full - false - bin\Debug-3.5\ - TRACE;DEBUG;NET35, JETBRAINS_ANNOTATIONS - prompt - 4 - true - - - pdbonly - true - bin\Release-3.5\ - TRACE;NET35, JETBRAINS_ANNOTATIONS - prompt - 4 - bin\Release-3.5\Manatee.Json.XML - - - true - - - Manatee.Json.snk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-3.5.project.json b/Manatee.Json/Manatee.Json-3.5.project.json deleted file mode 100644 index a0fb47c..0000000 --- a/Manatee.Json/Manatee.Json-3.5.project.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "frameworks": { - ".NETFramework,Version=v3.5,Profile=Client": {} - }, - "runtimes": { - "win": {} - }, - "buildOptions": { - "define": [ "TRACE", "NET45", "JETBRAINS_ANNOTATIONS" ], - "optimize": true, - "xmlDoc": true, - "keyFile": "Manatee.Json.snk" - } -} diff --git a/Manatee.Json/Manatee.Json-4.0.csproj b/Manatee.Json/Manatee.Json-4.0.csproj deleted file mode 100644 index 713293d..0000000 --- a/Manatee.Json/Manatee.Json-4.0.csproj +++ /dev/null @@ -1,311 +0,0 @@ - - - - - Debug - AnyCPU - {67AC4D8A-ACC2-4966-B60E-5B20B0AB6C4E} - Library - Properties - Manatee.Json - Manatee.Json - v4.0 - 512 - Client - - - true - full - false - bin\Debug-4.0\ - TRACE;DEBUG;NET4, JETBRAINS_ANNOTATIONS - prompt - 4 - true - - - pdbonly - true - bin\Release-4.0\ - TRACE;NET4, JETBRAINS_ANNOTATIONS - prompt - 4 - bin\Release-4.0\Manatee.Json.xml - - - true - - - Manatee.Json.snk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-4.0.project.json b/Manatee.Json/Manatee.Json-4.0.project.json deleted file mode 100644 index 565cf90..0000000 --- a/Manatee.Json/Manatee.Json-4.0.project.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "frameworks": { - ".NETFramework,Version=v4.0,Profile=Client": {} - }, - "runtimes": { - "win": {} - }, - "buildOptions": { - "define": [ "TRACE", "NET45", "JETBRAINS_ANNOTATIONS" ], - "optimize": true, - "xmlDoc": true, - "keyFile": "Manatee.Json.snk" - } -} diff --git a/Manatee.Json/Manatee.Json-4.5.csproj b/Manatee.Json/Manatee.Json-4.5.csproj deleted file mode 100644 index 86fd369..0000000 --- a/Manatee.Json/Manatee.Json-4.5.csproj +++ /dev/null @@ -1,439 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {6ADF0BCF-4E46-4605-A784-51EA6DAC81C7} - Library - Properties - Manatee.Json - Manatee.Json - 512 - - ..\ - true - - - v4.5 - true - full - false - bin\Debug-4.5\ - TRACE;DEBUG;NET45, JETBRAINS_ANNOTATIONS - prompt - 4 - - - false - true - - - true - - - Manatee.Json.snk - - - - - - bin\Release-4.5\ - TRACE;NET45, JETBRAINS_ANNOTATIONS - bin\Release-4.5\Manatee.Json.XML - true - pdbonly - AnyCPU - prompt - MinimumRecommendedRules.ruleset - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-4.5.csproj.user b/Manatee.Json/Manatee.Json-4.5.csproj.user deleted file mode 100644 index 07dbd5b..0000000 --- a/Manatee.Json/Manatee.Json-4.5.csproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - - ProjectFiles - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-4.5.project.json b/Manatee.Json/Manatee.Json-4.5.project.json deleted file mode 100644 index b39c42f..0000000 --- a/Manatee.Json/Manatee.Json-4.5.project.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "frameworks": { - ".NETFramework,Version=v4.0": {}, - ".NETFramework,Version=v4.5": {} - }, - "runtimes": { - "win": {} - }, - "buildOptions": { - "define": [ "TRACE", "NET45", "JETBRAINS_ANNOTATIONS" ], - "optimize": true, - "xmlDoc": true, - "keyFile": "Manatee.Json.snk" - } -} diff --git a/Manatee.Json/Manatee.Json-Core.xproj b/Manatee.Json/Manatee.Json-Core.xproj deleted file mode 100644 index 85ea3f4..0000000 --- a/Manatee.Json/Manatee.Json-Core.xproj +++ /dev/null @@ -1,26 +0,0 @@ - - - - 14.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - a83d9791-01a7-4031-886e-995b7a1320d1 - Manatee.Json - .\obj - .\bin\ - v4.5.2 - - - 2.0 - - - - - - - - - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-Core.xproj.user b/Manatee.Json/Manatee.Json-Core.xproj.user deleted file mode 100644 index c99c608..0000000 --- a/Manatee.Json/Manatee.Json-Core.xproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - - Start - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-Portable.csproj b/Manatee.Json/Manatee.Json-Portable.csproj deleted file mode 100644 index e8dda2e..0000000 --- a/Manatee.Json/Manatee.Json-Portable.csproj +++ /dev/null @@ -1,310 +0,0 @@ - - - - - 10.0 - Debug - AnyCPU - {B0A832B8-06B7-4494-8416-FABE755F621F} - Library - Properties - Manatee.Json - Manatee.Json - en-US - 512 - {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Profile111 - v4.5 - - - - - true - full - false - bin\Debug-Portable\ - TRACE;DEBUG;IOS, JETBRAINS_ANNOTATIONS - prompt - 4 - - - pdbonly - true - bin\Release-Portable\ - TRACE;IOS, JETBRAINS_ANNOTATIONS - prompt - 4 - bin\Release-Portable\Manatee.Json.XML - - - true - - - Manatee.Json.snk - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Manatee.Json/Manatee.Json-Portable.project.json b/Manatee.Json/Manatee.Json-Portable.project.json deleted file mode 100644 index 6782e01..0000000 --- a/Manatee.Json/Manatee.Json-Portable.project.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "frameworks": { - ".NETPortable,Version=v4.5,Profile=Profile111": {} - }, - "runtimes": { - "win": {} - }, - "buildOptions": { - "define": [ "TRACE", "NET45", "JETBRAINS_ANNOTATIONS" ], - "optimize": true, - "xmlDoc": true, - "keyFile": "Manatee.Json.snk" - } -} diff --git a/Manatee.Json/Manatee.Json.csproj b/Manatee.Json/Manatee.Json.csproj new file mode 100644 index 0000000..7a7599c --- /dev/null +++ b/Manatee.Json/Manatee.Json.csproj @@ -0,0 +1,50 @@ + + + + netstandard1.3;net46 + True + Provides an intuitive approach to building JSON structures. + 7.0.0 + Copyright © 2017 Little Crab Solutions + https://github.com/gregsdennis/Manatee.Json/blob/master/LICENSE.txt + https://github.com/gregsdennis/Manatee.Json + https://bytebucket.org/gregsdennis/manatee.json/wiki/Resources/Manatee-Json-Logo.png + + json manatee parser serializer jsonpath jsonschema transform path schema linq-to-json + v7.0.0 +BREAKING CHANGE: Frameworks below 4.6 are no longer supported. +Updated to multi-targeted NetStandard1.3 & NetFramework4.6. + +v6.0.3 +Schema passes latest version of JSON Schema Test Suite. (#63) + + True + Manatee.Json.snk + 7.0.0.0 + 7.0.0.0 + + + + .NETStandard + + + + .NETFramework + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Manatee.Json/Parsing/ArrayParser.cs b/Manatee.Json/Parsing/ArrayParser.cs index 3913629..bf31ec4 100644 --- a/Manatee.Json/Parsing/ArrayParser.cs +++ b/Manatee.Json/Parsing/ArrayParser.cs @@ -17,8 +17,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a index++; while (index < length) { - char c; - var message = source.SkipWhiteSpace(ref index, length, out c); + var message = source.SkipWhiteSpace(ref index, length, out char c); if (message != null) return message; // check for empty array if (c == ']') @@ -29,8 +28,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a } else return "Expected value."; // get value - JsonValue item; - message = JsonParser.Parse(source, ref index, out item); + message = JsonParser.Parse(source, ref index, out JsonValue item); array.Add(item); if (message != null) return message; message = source.SkipWhiteSpace(ref index, length, out c); @@ -52,8 +50,7 @@ public string TryParse(StreamReader stream, out JsonValue value) while (!stream.EndOfStream) { stream.Read(); // waste the '[' or ',' - char c; - var message = stream.SkipWhiteSpace(out c); + var message = stream.SkipWhiteSpace(out char c); if (message != null) return message; // check for empty array if (c == ']') @@ -64,8 +61,7 @@ public string TryParse(StreamReader stream, out JsonValue value) } else return "Expected value."; // get value - JsonValue item; - message = JsonParser.Parse(stream, out item); + message = JsonParser.Parse(stream, out JsonValue item); array.Add(item); if (message != null) return message; message = stream.SkipWhiteSpace(out c); diff --git a/Manatee.Json/Parsing/BoolParser.cs b/Manatee.Json/Parsing/BoolParser.cs index 808de58..41fd8b3 100644 --- a/Manatee.Json/Parsing/BoolParser.cs +++ b/Manatee.Json/Parsing/BoolParser.cs @@ -25,7 +25,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a count = 5; } count = Math.Min(count, source.Length - index); - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { buffer[i] = source[index + i]; } diff --git a/Manatee.Json/Parsing/JsonParser.cs b/Manatee.Json/Parsing/JsonParser.cs index 73ede35..332f879 100644 --- a/Manatee.Json/Parsing/JsonParser.cs +++ b/Manatee.Json/Parsing/JsonParser.cs @@ -13,9 +13,9 @@ internal static class JsonParser static JsonParser() { - Parsers = typeof(JsonParser).TypeInfo().Assembly.GetTypes() - .Where(t => typeof(IJsonParser).IsAssignableFrom(t) && t.TypeInfo().IsClass) - .Select(Activator.CreateInstance) + Parsers = typeof(JsonParser).GetTypeInfo().Assembly.DefinedTypes + .Where(t => typeof(IJsonParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) + .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() .ToList(); } @@ -23,16 +23,14 @@ static JsonParser() public static JsonValue Parse(string source) { var index = 0; - JsonValue value; - var errorMessage = Parse(source, ref index, out value); + var errorMessage = Parse(source, ref index, out JsonValue value); if (errorMessage != null) throw new JsonSyntaxException(errorMessage, value); return value; } public static JsonValue Parse(StreamReader stream) { - JsonValue value; - var errorMessage = Parse(stream, out value); + var errorMessage = Parse(stream, out JsonValue value); if (errorMessage != null) throw new JsonSyntaxException(errorMessage, value); return value; @@ -40,8 +38,7 @@ public static JsonValue Parse(StreamReader stream) public static string Parse(string source, ref int index, out JsonValue value, bool allowExtraChars = false) { var length = source.Length; - char c; - var errorMessage = source.SkipWhiteSpace(ref index, length, out c); + var errorMessage = source.SkipWhiteSpace(ref index, length, out char c); if (errorMessage != null) { value = null; @@ -58,8 +55,7 @@ public static string Parse(string source, ref int index, out JsonValue value, bo } public static string Parse(StreamReader stream, out JsonValue value) { - char c; - var errorMessage = stream.SkipWhiteSpace(out c); + var errorMessage = stream.SkipWhiteSpace(out char c); if (errorMessage != null) { value = null; diff --git a/Manatee.Json/Parsing/NullParser.cs b/Manatee.Json/Parsing/NullParser.cs index 3d5118c..ff706fc 100644 --- a/Manatee.Json/Parsing/NullParser.cs +++ b/Manatee.Json/Parsing/NullParser.cs @@ -12,7 +12,7 @@ public bool Handles(char c) public string TryParse(string source, ref int index, out JsonValue value, bool allowExtraChars) { var buffer = new char[4]; - for (int i = 0; i < 4 && index + i < source.Length; i++) + for (var i = 0; i < 4 && index + i < source.Length; i++) { buffer[i] = source[index + i]; } @@ -29,7 +29,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a public string TryParse(StreamReader stream, out JsonValue value) { var buffer = new char[4]; - for (int i = 0; i < 4 && !stream.EndOfStream; i++) + for (var i = 0; i < 4 && !stream.EndOfStream; i++) { buffer[i] = (char) stream.Read(); } diff --git a/Manatee.Json/Parsing/NumberParser.cs b/Manatee.Json/Parsing/NumberParser.cs index 390f1eb..416939f 100644 --- a/Manatee.Json/Parsing/NumberParser.cs +++ b/Manatee.Json/Parsing/NumberParser.cs @@ -20,7 +20,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a var bufferSize = 0; var bufferLength = FibSequence[bufferSize]; var buffer = new char[bufferLength]; - int bufferIndex = 0; + var bufferIndex = 0; var sourceLength = source.Length; while (index < sourceLength) { @@ -46,9 +46,8 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a index++; bufferIndex++; } - double dbl; var result = new string(buffer, 0, bufferIndex); - if (!double.TryParse(result, NumberStyles.Any, CultureInfo.InvariantCulture, out dbl)) + if (!double.TryParse(result, NumberStyles.Any, CultureInfo.InvariantCulture, out double dbl)) { value = null; return $"Value not recognized: '{result}'"; @@ -61,7 +60,7 @@ public string TryParse(StreamReader stream, out JsonValue value) var bufferSize = 0; var bufferLength = FibSequence[bufferSize]; var buffer = new char[bufferLength]; - int bufferIndex = 0; + var bufferIndex = 0; while (!stream.EndOfStream) { if (bufferIndex == bufferLength) @@ -84,9 +83,8 @@ public string TryParse(StreamReader stream, out JsonValue value) buffer[bufferIndex] = c; bufferIndex++; } - double dbl; var result = new string(buffer, 0, bufferIndex); - if (!double.TryParse(result, NumberStyles.Any, CultureInfo.InvariantCulture, out dbl)) + if (!double.TryParse(result, NumberStyles.Any, CultureInfo.InvariantCulture, out double dbl)) { value = null; return $"Value not recognized: '{result}'"; diff --git a/Manatee.Json/Parsing/ObjectParser.cs b/Manatee.Json/Parsing/ObjectParser.cs index 5a2380e..bb8faa5 100644 --- a/Manatee.Json/Parsing/ObjectParser.cs +++ b/Manatee.Json/Parsing/ObjectParser.cs @@ -17,8 +17,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a index++; while (index < length) { - char c; - var message = source.SkipWhiteSpace(ref index, length, out c); + var message = source.SkipWhiteSpace(ref index, length, out char c); if (message != null) return message; // check for empty object if (c == '}') @@ -32,8 +31,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a message = source.SkipWhiteSpace(ref index, length, out c); if (message != null) return message; if (c != '\"') return "Expected key."; - JsonValue item; - message = JsonParser.Parse(source, ref index, out item); + message = JsonParser.Parse(source, ref index, out JsonValue item); if (message != null) return message; var key = item.String; // check for colon @@ -68,8 +66,7 @@ public string TryParse(StreamReader stream, out JsonValue value) while (!stream.EndOfStream) { stream.Read(); // waste the '{' or ',' - char c; - var message = stream.SkipWhiteSpace(out c); + var message = stream.SkipWhiteSpace(out char c); if (message != null) return message; // check for empty object if (c == '}') @@ -83,8 +80,7 @@ public string TryParse(StreamReader stream, out JsonValue value) message = stream.SkipWhiteSpace(out c); if (message != null) return message; if (c != '\"') return "Expected key."; - JsonValue item; - message = JsonParser.Parse(stream, out item); + message = JsonParser.Parse(stream, out JsonValue item); if (message != null) return message; var key = item.String; // check for colon diff --git a/Manatee.Json/Parsing/StringParser.cs b/Manatee.Json/Parsing/StringParser.cs index e62707a..eae1aa0 100644 --- a/Manatee.Json/Parsing/StringParser.cs +++ b/Manatee.Json/Parsing/StringParser.cs @@ -50,8 +50,7 @@ public string TryParse(string source, ref int index, out JsonValue value, bool a return "Could not find end of string value."; } var result = new string(buffer, 0, bufferIndex); - string escaped; - var errorMessage = result.EvaluateEscapeSequences(out escaped); + var errorMessage = result.EvaluateEscapeSequences(out string escaped); value = escaped; return errorMessage; } @@ -91,8 +90,7 @@ public string TryParse(StreamReader stream, out JsonValue value) return "Could not find end of string value."; } var result = new string(buffer, 0, bufferIndex); - string escaped; - var errorMessage = result.EvaluateEscapeSequences(out escaped); + var errorMessage = result.EvaluateEscapeSequences(out string escaped); value = escaped; return errorMessage; } diff --git a/Manatee.Json/Path/ArrayParameters/SliceQuery.cs b/Manatee.Json/Path/ArrayParameters/SliceQuery.cs index be2a817..f20e6cf 100644 --- a/Manatee.Json/Path/ArrayParameters/SliceQuery.cs +++ b/Manatee.Json/Path/ArrayParameters/SliceQuery.cs @@ -10,8 +10,6 @@ internal class SliceQuery : IJsonPathArrayQuery, IEquatable internal IEnumerable Slices { get; } public SliceQuery(params Slice[] slices) - : this((IEnumerable) slices) {} - public SliceQuery(IEnumerable slices) { Slices = slices.ToList(); } @@ -21,7 +19,7 @@ public IEnumerable Find(JsonArray json, JsonValue root) } public override string ToString() { - return Slices.Join(","); + return string.Join(",", Slices); } public bool Equals(SliceQuery other) { diff --git a/Manatee.Json/Path/Expressions/ArrayIndexExpression.cs b/Manatee.Json/Path/Expressions/ArrayIndexExpression.cs index 769e327..5455208 100644 --- a/Manatee.Json/Path/Expressions/ArrayIndexExpression.cs +++ b/Manatee.Json/Path/Expressions/ArrayIndexExpression.cs @@ -20,7 +20,7 @@ public override object Evaluate(T json, JsonValue root) if (results.Count > 1) throw new InvalidOperationException($"Path '{Path}' returned more than one result on value '{value}'"); var result = results.FirstOrDefault(); - var index = GetIndex(); + var index = _GetIndex(); if (result != null && index >= 0) { if (result.Type == JsonValueType.Array && index < result.Array.Count) @@ -33,7 +33,7 @@ public override object Evaluate(T json, JsonValue root) public override string ToString() { var path = Path == null ? string.Empty : Path.GetRawString(); - return string.Format(IsLocal ? "@{0}[{1}]" : "${0}[{1}]", path, GetIndex()); + return string.Format(IsLocal ? "@{0}[{1}]" : "${0}[{1}]", path, _GetIndex()); } public bool Equals(ArrayIndexExpression other) { @@ -58,7 +58,7 @@ public override int GetHashCode() } } - private int GetIndex() + private int _GetIndex() { var value = IndexExpression?.Evaluate(default(T), null); if (value != null) return (int) value; diff --git a/Manatee.Json/Path/Expressions/ConversionExpression.cs b/Manatee.Json/Path/Expressions/ConversionExpression.cs index c41b67d..0693cf8 100644 --- a/Manatee.Json/Path/Expressions/ConversionExpression.cs +++ b/Manatee.Json/Path/Expressions/ConversionExpression.cs @@ -13,7 +13,7 @@ internal class ConversionExpression : ExpressionTreeNode, IEquatable 1) throw new InvalidOperationException($"Path '{Path}' returned more than one result on value '{value}'"); var result = results.FirstOrDefault(); - var parameter = GetParameter(); + var parameter = _GetParameter(); return result != null && result.Type == JsonValueType.Array && parameter != null ? result.Array.IndexOf(parameter) : (object)null; @@ -52,7 +52,7 @@ public override int GetHashCode() } } - private JsonValue GetParameter() + private JsonValue _GetParameter() { var value = ParameterExpression?.Evaluate(null, null); if (value != null) diff --git a/Manatee.Json/Path/Expressions/IsGreaterThanExpression.cs b/Manatee.Json/Path/Expressions/IsGreaterThanExpression.cs index 57c9305..df3159c 100644 --- a/Manatee.Json/Path/Expressions/IsGreaterThanExpression.cs +++ b/Manatee.Json/Path/Expressions/IsGreaterThanExpression.cs @@ -24,8 +24,7 @@ public bool Equals(IsGreaterThanExpression other) } public override bool Equals(object obj) { - if (obj.GetType() != this.GetType()) return false; - return Equals((IsGreaterThanExpression) obj); + return Equals(obj as IsGreaterThanExpression); } public override int GetHashCode() { diff --git a/Manatee.Json/Path/Expressions/LengthExpression.cs b/Manatee.Json/Path/Expressions/LengthExpression.cs index 7f2ac49..7185db8 100644 --- a/Manatee.Json/Path/Expressions/LengthExpression.cs +++ b/Manatee.Json/Path/Expressions/LengthExpression.cs @@ -19,7 +19,7 @@ public override object Evaluate(T json, JsonValue root) if (array == null) { var value = json as JsonValue; - if (value.Type == JsonValueType.Array) + if (value?.Type == JsonValueType.Array) array = value.Array; } if (array == null) return null; diff --git a/Manatee.Json/Path/Expressions/NameExpresssion.cs b/Manatee.Json/Path/Expressions/NameExpresssion.cs index fe36471..c3f77fb 100644 --- a/Manatee.Json/Path/Expressions/NameExpresssion.cs +++ b/Manatee.Json/Path/Expressions/NameExpresssion.cs @@ -20,7 +20,7 @@ public override object Evaluate(T json, JsonValue root) if (results.Count > 1) throw new InvalidOperationException($"Path '{Path}' returned more than one result on value '{value}'"); var result = results.FirstOrDefault(); - var name = GetName(); + var name = _GetName(); return result != null && result.Type == JsonValueType.Object && result.Object.ContainsKey(name) ? result.Object[name].GetValue() : null; @@ -28,10 +28,10 @@ public override object Evaluate(T json, JsonValue root) public override string ToString() { var path = Path == null ? string.Empty : Path.GetRawString(); - return string.Format(IsLocal ? "@{0}.{1}" : "${0}.{1}", path, GetName()); + return string.Format(IsLocal ? "@{0}.{1}" : "${0}.{1}", path, _GetName()); } - private string GetName() + private string _GetName() { var value = NameExp?.Evaluate(default(T), null); if (value != null) diff --git a/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs b/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs index fb07a4e..6d7911e 100644 --- a/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs +++ b/Manatee.Json/Path/Expressions/Parsing/JsonPathExpressionParser.cs @@ -12,17 +12,16 @@ internal static class JsonPathExpressionParser static JsonPathExpressionParser() { - Parsers = typeof(JsonPathExpressionParser).TypeInfo().Assembly.GetTypes() - .Where(t => typeof(IJsonPathExpressionParser).IsAssignableFrom(t) && t.TypeInfo().IsClass) - .Select(Activator.CreateInstance) + Parsers = typeof(JsonPathExpressionParser).GetTypeInfo().Assembly.DefinedTypes + .Where(t => typeof(IJsonPathExpressionParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) + .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() .ToList(); } public static string Parse(string source, ref int index, out Expression expr) { - ExpressionTreeNode root; - var error = Parse(source, ref index, out root); + var error = Parse(source, ref index, out ExpressionTreeNode root); if (error != null) { expr = null; @@ -45,8 +44,7 @@ public static string Parse(string source, ref int index, out ExpressionTree root = null; do { - char c; - var errorMessage = source.SkipWhiteSpace(ref index, length, out c); + var errorMessage = source.SkipWhiteSpace(ref index, length, out char c); if (errorMessage != null) return errorMessage; var substring = source.Substring(index); var parser = Parsers.FirstOrDefault(p => p.Handles(substring)); @@ -58,46 +56,43 @@ public static string Parse(string source, ref int index, out ExpressionTree } while (index < length && node != null); root = nodes.Count == 1 - ? CheckNode(nodes[0], null) - : BuildTree(nodes); + ? _CheckNode(nodes[0], null) + : _BuildTree(nodes); return null; } - private static ExpressionTreeNode BuildTree(List> nodes) + private static ExpressionTreeNode _BuildTree(List> nodes) { if (!nodes.Any()) return null; var minPriority = nodes.Min(n => n.Priority); var root = nodes.Last(n => n.Priority == minPriority); - var branch = root as ExpressionTreeBranch; - if (branch != null && branch.Right == null && branch.Left == null) + if (root is ExpressionTreeBranch branch && branch.Right == null && branch.Left == null) { var split = nodes.LastIndexOf(root); var left = nodes.Take(split).ToList(); var right = nodes.Skip(split + 1).ToList(); - branch.Left = CheckNode(BuildTree(left), branch); - branch.Right = CheckNode(BuildTree(right), branch); + branch.Left = _CheckNode(_BuildTree(left), branch); + branch.Right = _CheckNode(_BuildTree(right), branch); } - var not = root as NotExpression; - if (not != null) + if (root is NotExpression not) { var split = nodes.IndexOf(root); var right = nodes.Skip(split + 1).FirstOrDefault(); - not.Root = CheckNode(right, null); + not.Root = _CheckNode(right, null); } return root; } - private static ExpressionTreeNode CheckNode(ExpressionTreeNode node, ExpressionTreeBranch root) + private static ExpressionTreeNode _CheckNode(ExpressionTreeNode node, ExpressionTreeBranch root) { - var named = node as NameExpression; - if (named != null && (root == null || root.Priority == 0)) + if (node is NameExpression named && (root == null || root.Priority == 0)) { return new HasPropertyExpression - { - Path = named.Path, - IsLocal = named.IsLocal, - Name = named.Name - }; + { + Path = named.Path, + IsLocal = named.IsLocal, + Name = named.Name + }; } return node; } diff --git a/Manatee.Json/Path/Expressions/Parsing/PathExpressionParser.cs b/Manatee.Json/Path/Expressions/Parsing/PathExpressionParser.cs index 1f8e19c..98d2241 100644 --- a/Manatee.Json/Path/Expressions/Parsing/PathExpressionParser.cs +++ b/Manatee.Json/Path/Expressions/Parsing/PathExpressionParser.cs @@ -17,8 +17,7 @@ public bool Handles(string input) public string TryParse(string source, ref int index, out ExpressionTreeNode node) { var isLocal = source[index] == '@'; - JsonPath path; - var error = JsonPathParser.Parse(source, ref index, out path); + var error = JsonPathParser.Parse(source, ref index, out JsonPath path); // Swallow this error from the path parser and assume the path just ended. // If it's really a syntax error, the expression parser should catch it. if (error != null && error != "Unrecognized JSON Path element.") @@ -35,14 +34,13 @@ public string TryParse(string source, ref int index, out ExpressionTreeNode Translate(Expression body) if (add == null) throw new InvalidOperationException(); return new AddExpression - { - Left = ExpressionTranslator.TranslateNode(add.Left), - Right = ExpressionTranslator.TranslateNode(add.Right) - }; + { + Left = ExpressionTranslator.TranslateNode(add.Left), + Right = ExpressionTranslator.TranslateNode(add.Right) + }; } } } \ No newline at end of file diff --git a/Manatee.Json/Path/Expressions/Translation/AndExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/AndExpressionTranslator.cs index efccbf7..d7d98f2 100644 --- a/Manatee.Json/Path/Expressions/Translation/AndExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/AndExpressionTranslator.cs @@ -11,10 +11,10 @@ public ExpressionTreeNode Translate(Expression body) if (and == null) throw new InvalidOperationException(); return new AndExpression - { - Left = ExpressionTranslator.TranslateNode(and.Left), - Right = ExpressionTranslator.TranslateNode(and.Right) - }; + { + Left = ExpressionTranslator.TranslateNode(and.Left), + Right = ExpressionTranslator.TranslateNode(and.Right) + }; } } } \ No newline at end of file diff --git a/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs index 5d781e0..bc774d8 100644 --- a/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/ExpressionTranslator.cs @@ -12,14 +12,14 @@ internal static class ExpressionTranslator private static readonly Dictionary> Translators = new Dictionary> { - {typeof(ConstantExpression), GetValueTranslator}, - {typeof(BinaryExpression), e => GetNodeTypeBasedTranslator(e.NodeType)}, - {typeof(UnaryExpression), e => GetNodeTypeBasedTranslator(e.NodeType)}, - {typeof(MethodCallExpression), GetMethodCallTranslator}, - {typeof(MemberExpression), GetMemberTranslator}, + {typeof(ConstantExpression), _GetValueTranslator}, + {typeof(BinaryExpression), e => _GetNodeTypeBasedTranslator(e.NodeType)}, + {typeof(UnaryExpression), e => _GetNodeTypeBasedTranslator(e.NodeType)}, + {typeof(MethodCallExpression), _GetMethodCallTranslator}, + {typeof(MemberExpression), _GetMemberTranslator}, }; - private static IExpressionTranslator GetValueTranslator(Expression e) + private static IExpressionTranslator _GetValueTranslator(Expression e) { var type = e.Type; if (type == typeof(bool)) @@ -34,7 +34,7 @@ private static IExpressionTranslator GetValueTranslator(Expression e) return new NullValueExpressionTranslator(); throw new NotSupportedException($"Values of type '{type}' are not supported."); } - private static IExpressionTranslator GetNodeTypeBasedTranslator(ExpressionType type) + private static IExpressionTranslator _GetNodeTypeBasedTranslator(ExpressionType type) { switch (type) { @@ -102,7 +102,6 @@ private static IExpressionTranslator GetNodeTypeBasedTranslator(ExpressionType t case ExpressionType.RightShift: case ExpressionType.TypeAs: case ExpressionType.TypeIs: -#if NET4 || NET45 case ExpressionType.Assign: case ExpressionType.Block: case ExpressionType.DebugInfo: @@ -142,12 +141,11 @@ private static IExpressionTranslator GetNodeTypeBasedTranslator(ExpressionType t case ExpressionType.OnesComplement: case ExpressionType.IsTrue: case ExpressionType.IsFalse: -#endif break; } throw new NotSupportedException($"Expression type '{type}' is not supported."); } - private static IExpressionTranslator GetMethodCallTranslator(Expression exp) + private static IExpressionTranslator _GetMethodCallTranslator(Expression exp) { var method = (MethodCallExpression) exp; switch (method.Method.Name) @@ -165,7 +163,7 @@ private static IExpressionTranslator GetMethodCallTranslator(Expression exp) } throw new NotSupportedException($"The method '{method.Method.Name}' is not supported."); } - private static IExpressionTranslator GetMemberTranslator(Expression exp) + private static IExpressionTranslator _GetMemberTranslator(Expression exp) { var member = (MemberExpression) exp; if (member.Member is FieldInfo && member.Expression is ConstantExpression) @@ -176,7 +174,8 @@ private static IExpressionTranslator GetMemberTranslator(Expression exp) public static ExpressionTreeNode TranslateNode(Expression source) { var type = source.GetType(); - var expressionKey = Translators.Keys.FirstOrDefault(t => t.IsAssignableFrom(type)); + var typeInfo = type.GetTypeInfo(); + var expressionKey = Translators.Keys.FirstOrDefault(t => t.GetTypeInfo().IsAssignableFrom(typeInfo)); if (expressionKey != null) { var translator = Translators[expressionKey](source); diff --git a/Manatee.Json/Path/Expressions/Translation/FieldExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/FieldExpressionTranslator.cs index 28abb7b..ed94a35 100644 --- a/Manatee.Json/Path/Expressions/Translation/FieldExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/FieldExpressionTranslator.cs @@ -7,12 +7,12 @@ internal class FieldExpressionTranslator : IExpressionTranslator { public ExpressionTreeNode Translate(Expression body) { - var member = (MemberExpression)body; + var member = (MemberExpression) body; return new FieldExpression - { - Field = (FieldInfo)member.Member, - Source = ((ConstantExpression)member.Expression).Value - }; + { + Field = (FieldInfo) member.Member, + Source = ((ConstantExpression) member.Expression).Value + }; } } } \ No newline at end of file diff --git a/Manatee.Json/Path/Expressions/Translation/HasPropertyExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/HasPropertyExpressionTranslator.cs index 2062f58..27bf556 100644 --- a/Manatee.Json/Path/Expressions/Translation/HasPropertyExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/HasPropertyExpressionTranslator.cs @@ -8,7 +8,6 @@ internal class HasPropertyExpressionTranslator : PathExpressionTranslator { public override ExpressionTreeNode Translate(Expression body) { - bool isLocal; var method = body as MethodCallExpression; if (method == null) throw new InvalidOperationException(); @@ -17,7 +16,7 @@ public override ExpressionTreeNode Translate(Expression body) throw new NotSupportedException("Only constant string arguments are supported in HasProperty()"); return new HasPropertyExpression { - Path = BuildPath(method, out isLocal), + Path = BuildPath(method, out bool isLocal), IsLocal = isLocal, Name = parameter.Value.ToString() }; diff --git a/Manatee.Json/Path/Expressions/Translation/IsEqualExpressionTranslator.cs b/Manatee.Json/Path/Expressions/Translation/IsEqualExpressionTranslator.cs index 17f81c8..9e12963 100644 --- a/Manatee.Json/Path/Expressions/Translation/IsEqualExpressionTranslator.cs +++ b/Manatee.Json/Path/Expressions/Translation/IsEqualExpressionTranslator.cs @@ -11,10 +11,10 @@ public ExpressionTreeNode Translate(Expression body) if (equal == null) throw new InvalidOperationException(); return new IsEqualExpression - { - Left = ExpressionTranslator.TranslateNode(equal.Left), - Right = ExpressionTranslator.TranslateNode(equal.Right) - }; + { + Left = ExpressionTranslator.TranslateNode(equal.Left), + Right = ExpressionTranslator.TranslateNode(equal.Right) + }; } } } \ No newline at end of file diff --git a/Manatee.Json/Path/Expressions/ValueComparer.cs b/Manatee.Json/Path/Expressions/ValueComparer.cs index ec10fcd..63ac4b1 100644 --- a/Manatee.Json/Path/Expressions/ValueComparer.cs +++ b/Manatee.Json/Path/Expressions/ValueComparer.cs @@ -7,40 +7,40 @@ internal static class ValueComparer { public static bool Equal(object a, object b) { - var sleft = TryGetString(a); - var sright = TryGetString(b); + var sleft = _TryGetString(a); + var sright = _TryGetString(b); if (sleft != null && sright != null) return string.Compare(sleft, sright, StringComparison.Ordinal) == 0; - var bleft = TryGetBoolean(a); - var bright = TryGetBoolean(b); + var bleft = _TryGetBoolean(a); + var bright = _TryGetBoolean(b); if (bleft != null && bright != null) return bleft == bright; - var dleft = TryGetNumber(a); - var dright = TryGetNumber(b); + var dleft = _TryGetNumber(a); + var dright = _TryGetNumber(b); if (dleft != null && dright != null) return dleft == dright; return false; } public static bool LessThan(object a, object b) { - var sleft = TryGetString(a); - var sright = TryGetString(b); + var sleft = _TryGetString(a); + var sright = _TryGetString(b); if (sleft != null && sright != null) return string.Compare(sleft, sright, StringComparison.Ordinal) < 0; - var dleft = TryGetNumber(a); - var dright = TryGetNumber(b); + var dleft = _TryGetNumber(a); + var dright = _TryGetNumber(b); if (dleft != null && dright != null) return dleft < dright; return false; } public static bool GreaterThan(object a, object b) { - var sleft = TryGetString(a); - var sright = TryGetString(b); + var sleft = _TryGetString(a); + var sright = _TryGetString(b); if (sleft != null && sright != null) return string.Compare(sleft, sright, StringComparison.Ordinal) > 0; - var dleft = TryGetNumber(a); - var dright = TryGetNumber(b); + var dleft = _TryGetNumber(a); + var dright = _TryGetNumber(b); if (dleft != null && dright != null) return dleft > dright; return false; @@ -48,35 +48,35 @@ public static bool GreaterThan(object a, object b) public static bool LessThanEqual(object a, object b) { - var sleft = TryGetString(a); - var sright = TryGetString(b); + var sleft = _TryGetString(a); + var sright = _TryGetString(b); if (sleft != null && sright != null) return string.Compare(sleft, sright, StringComparison.Ordinal) <= 0; - var dleft = TryGetNumber(a); - var dright = TryGetNumber(b); + var dleft = _TryGetNumber(a); + var dright = _TryGetNumber(b); if (dleft != null && dright != null) return dleft <= dright; return false; } public static bool GreaterThanEqual(object a, object b) { - var sleft = TryGetString(a); - var sright = TryGetString(b); + var sleft = _TryGetString(a); + var sright = _TryGetString(b); if (sleft != null && sright != null) return string.Compare(sleft, sright, StringComparison.Ordinal) >= 0; - var dleft = TryGetNumber(a); - var dright = TryGetNumber(b); + var dleft = _TryGetNumber(a); + var dright = _TryGetNumber(b); if (dleft != null && dright != null) return dleft >= dright; return false; } - private static string TryGetString(object value) + private static string _TryGetString(object value) { var jv = value as JsonValue; return jv != null && jv.Type == JsonValueType.String ? jv.String : value as string; } - private static double? TryGetNumber(object value) + private static double? _TryGetNumber(object value) { var jv = value as JsonValue; if (jv != null && jv.Type == JsonValueType.Number) return jv.Number; @@ -84,7 +84,7 @@ private static string TryGetString(object value) // at this point, we have no idea what this is. return null; } - private static bool? TryGetBoolean(object value) + private static bool? _TryGetBoolean(object value) { var jv = value as JsonValue; return jv != null && jv.Type == JsonValueType.Boolean ? jv.Boolean : value as bool?; diff --git a/Manatee.Json/Path/JsonPath.cs b/Manatee.Json/Path/JsonPath.cs index 8f985d3..79fb183 100644 --- a/Manatee.Json/Path/JsonPath.cs +++ b/Manatee.Json/Path/JsonPath.cs @@ -74,7 +74,7 @@ public override int GetHashCode() internal string GetRawString() { - return Operators.Select(o => o.ToString()).Join(string.Empty); + return string.Join(string.Empty, Operators.Select(o => o.ToString())); } } } \ No newline at end of file diff --git a/Manatee.Json/Path/JsonPathSyntaxException.cs b/Manatee.Json/Path/JsonPathSyntaxException.cs index dc60205..4d41d1f 100644 --- a/Manatee.Json/Path/JsonPathSyntaxException.cs +++ b/Manatee.Json/Path/JsonPathSyntaxException.cs @@ -6,9 +6,6 @@ namespace Manatee.Json.Path /// /// Thrown when an input string contains a syntax error while parsing a . /// -#if !IOS && !CORE - [Serializable] -#endif public class JsonPathSyntaxException : Exception { private readonly bool _isExpression; diff --git a/Manatee.Json/Path/JsonPathWith.cs b/Manatee.Json/Path/JsonPathWith.cs index 572e8d4..5f2a2c0 100644 --- a/Manatee.Json/Path/JsonPathWith.cs +++ b/Manatee.Json/Path/JsonPathWith.cs @@ -96,21 +96,6 @@ public static JsonPath SearchArray(params Slice[] slices) return path; } /// - /// Appends a by specifying a series of array indicies using array slice notation. - /// - /// The start index of the s to include. - /// The end index of the s to include. - /// The index interval of the s to include. - /// The new . - /// The format for the array slice is [start:end:step]. All parameters are individually optional, - /// however either the start or end must be defines. Negative values for start and end indicate that the - /// iterator should begin counting from the end of the array. - [Obsolete("Use the SearchArray(params Slice[]) overload instead.")] - public static JsonPath SearchArraySlice(int? start, int? end, int? step = null) - { - return SearchArray(new Slice(start, end, step)); - } - /// /// Appends a by specifying an expression which evaluates to the index to include. /// /// The expression. @@ -146,21 +131,6 @@ public static JsonPath Array(params Slice[] slices) return path; } /// - /// Appends a by specifying a series of array indicies using array slice notation. - /// - /// The start index of the s to include. - /// The end index of the s to include. - /// The index interval of the s to include. - /// The new . - /// The format for the array slice is [start:end:step]. All parameters are individually optional, - /// however either the start or end must be defines. Negative values for start and end indicate that the - /// iterator should begin counting from the end of the array. - [Obsolete("Use the Array(params Slice[]) overload instead.")] - public static JsonPath ArraySlice(int? start, int? end, int? step = null) - { - return Array(new Slice(start, end, step)); - } - /// /// Appends a by specifying an expression which evaluates to the index to include. /// /// The expression. @@ -333,22 +303,6 @@ public static JsonPath Array(this JsonPath path, params Slice[] slices) return newPath; } /// - /// Appends a by specifying a series of array indicies using array slice notation. - /// - /// The to extend. - /// The start index of the s to include. - /// The end index of the s to include. - /// The index interval of the s to include. - /// The new . - /// The format for the array slice is [start:end:step]. All parameters are individually optional, - /// however either the start or end must be defines. Negative values for start and end indicate that the - /// iterator should begin counting from the end of the array. - [Obsolete("Use the Array(this JsonPath, params Slice[]) overload instead.")] - public static JsonPath ArraySlice(this JsonPath path, int? start, int? end, int? step = null) - { - return path.Array(new Slice(start, end, step)); - } - /// /// Appends a by specifying an expression which evaluates to the index to include. /// /// The to extend. diff --git a/Manatee.Json/Path/Operators/ArrayOperator.cs b/Manatee.Json/Path/Operators/ArrayOperator.cs index dbf2a8c..770fc2e 100644 --- a/Manatee.Json/Path/Operators/ArrayOperator.cs +++ b/Manatee.Json/Path/Operators/ArrayOperator.cs @@ -20,7 +20,7 @@ public JsonArray Evaluate(JsonArray json, JsonValue root) : v.Type == JsonValueType.Object ? Query.Find(v.Object.Values.ToJson(), root) : Enumerable.Empty()) - .NotNull()); + .WhereNotNull()); } public override string ToString() diff --git a/Manatee.Json/Path/Operators/NameOperator.cs b/Manatee.Json/Path/Operators/NameOperator.cs index 27c81b4..d391f36 100644 --- a/Manatee.Json/Path/Operators/NameOperator.cs +++ b/Manatee.Json/Path/Operators/NameOperator.cs @@ -17,11 +17,11 @@ public JsonArray Evaluate(JsonArray json, JsonValue root) { return new JsonArray(json.Select(v => v.Type == JsonValueType.Object && v.Object.ContainsKey(Name) ? v.Object[Name] - : null).NotNull()); + : null).WhereNotNull()); } public override string ToString() { - return Name.Any(c => !char.IsLetterOrDigit(c)) || Name.IsNullOrWhiteSpace() + return Name.Any(c => !char.IsLetterOrDigit(c)) || string.IsNullOrWhiteSpace(Name) ? $".'{Name}'" : $".{Name}"; } diff --git a/Manatee.Json/Path/Operators/WildCardOperator.cs b/Manatee.Json/Path/Operators/WildCardOperator.cs index 99866f8..b545c51 100644 --- a/Manatee.Json/Path/Operators/WildCardOperator.cs +++ b/Manatee.Json/Path/Operators/WildCardOperator.cs @@ -27,7 +27,7 @@ public JsonArray Evaluate(JsonArray json, JsonValue root) default: return Enumerable.Empty(); } - }).NotNull()); + }).WhereNotNull()); } public override string ToString() { diff --git a/Manatee.Json/Path/Parsing/ExpressionFilterParser.cs b/Manatee.Json/Path/Parsing/ExpressionFilterParser.cs index 536e65f..9101d43 100644 --- a/Manatee.Json/Path/Parsing/ExpressionFilterParser.cs +++ b/Manatee.Json/Path/Parsing/ExpressionFilterParser.cs @@ -20,10 +20,8 @@ public string TryParse(string source, ref int index, ref JsonPath path) if (error != null) return error; - if (index >= source.Length) - return "Unexpected end of input."; - if (source[index] != ']') - return "Expected ']'"; + if (index >= source.Length) return "Unexpected end of input."; + if (source[index] != ']') return "Expected ']'"; index++; path.Operators.Add(new ArrayOperator(new FilterExpressionQuery(expression))); return null; diff --git a/Manatee.Json/Path/Parsing/ExpressionIndexParser.cs b/Manatee.Json/Path/Parsing/ExpressionIndexParser.cs index 60f4e85..ed9e058 100644 --- a/Manatee.Json/Path/Parsing/ExpressionIndexParser.cs +++ b/Manatee.Json/Path/Parsing/ExpressionIndexParser.cs @@ -20,10 +20,8 @@ public string TryParse(string source, ref int index, ref JsonPath path) if (error != null) return error; - if (index >= source.Length) - return "Unexpected end of input."; - if (source[index] != ']') - return "Expected ']'"; + if (index >= source.Length) return "Unexpected end of input."; + if (source[index] != ']') return "Expected ']'"; index++; path.Operators.Add(new ArrayOperator(new IndexExpressionQuery(expression))); return null; diff --git a/Manatee.Json/Path/Parsing/IndexedArrayParser.cs b/Manatee.Json/Path/Parsing/IndexedArrayParser.cs index ef53884..dad5820 100644 --- a/Manatee.Json/Path/Parsing/IndexedArrayParser.cs +++ b/Manatee.Json/Path/Parsing/IndexedArrayParser.cs @@ -12,11 +12,9 @@ public bool Handles(string input) } public string TryParse(string source, ref int index, ref JsonPath path) { - if (path == null) - return "Start token not found."; + if (path == null) return "Start token not found."; - IList slices; - var error = source.GetSlices(ref index, out slices); + var error = source.GetSlices(ref index, out IList slices); if (error != null) return error; path = path.Array(slices.ToArray()); diff --git a/Manatee.Json/Path/Parsing/JsonPathParser.cs b/Manatee.Json/Path/Parsing/JsonPathParser.cs index 3ad1ee2..1b65358 100644 --- a/Manatee.Json/Path/Parsing/JsonPathParser.cs +++ b/Manatee.Json/Path/Parsing/JsonPathParser.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using Manatee.Json.Internal; namespace Manatee.Json.Path.Parsing @@ -11,9 +12,9 @@ internal static class JsonPathParser static JsonPathParser() { - Parsers = typeof(JsonPathParser).TypeInfo().Assembly.GetTypes() - .Where(t => typeof(IJsonPathParser).IsAssignableFrom(t) && t.TypeInfo().IsClass) - .Select(Activator.CreateInstance) + Parsers = typeof(JsonPathParser).GetTypeInfo().Assembly.DefinedTypes + .Where(t => typeof(IJsonPathParser).GetTypeInfo().IsAssignableFrom(t) && t.IsClass) + .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() .ToList(); } @@ -21,8 +22,7 @@ static JsonPathParser() public static JsonPath Parse(string source) { var index = 0; - JsonPath path; - var errorMessage = Parse(source, ref index, out path); + var errorMessage = Parse(source, ref index, out JsonPath path); if (errorMessage != null) throw new JsonPathSyntaxException(path, errorMessage); return path; @@ -33,8 +33,7 @@ public static string Parse(string source, ref int index, out JsonPath path) path = null; while(index < length) { - char c; - var errorMessage = source.SkipWhiteSpace(ref index, length, out c); + var errorMessage = source.SkipWhiteSpace(ref index, length, out char c); if (errorMessage != null) return errorMessage; var substring = source.Substring(index); var parser = Parsers.FirstOrDefault(p => p.Handles(substring)); diff --git a/Manatee.Json/Path/Parsing/PathParsingExtensions.cs b/Manatee.Json/Path/Parsing/PathParsingExtensions.cs index 4ad3e45..3c4f5f8 100644 --- a/Manatee.Json/Path/Parsing/PathParsingExtensions.cs +++ b/Manatee.Json/Path/Parsing/PathParsingExtensions.cs @@ -14,11 +14,11 @@ internal static class PathParsingExtensions public static string GetKey(this string source, ref int index, out string key) { return source[index].In('"', '\'') - ? GetQuotedKey(source, ref index, out key) - : GetBasicKey(source, ref index, out key); + ? _GetQuotedKey(source, ref index, out key) + : _GetBasicKey(source, ref index, out key); } - private static string GetBasicKey(string source, ref int index, out string key) + private static string _GetBasicKey(string source, ref int index, out string key) { var bufferSize = 0; var bufferLength = FibSequence[bufferSize]; @@ -59,7 +59,7 @@ private static string GetBasicKey(string source, ref int index, out string key) return null; } - private static string GetQuotedKey(string source, ref int index, out string key) + private static string _GetQuotedKey(string source, ref int index, out string key) { var bufferSize = 0; var bufferLength = FibSequence[bufferSize]; @@ -98,8 +98,7 @@ private static string GetQuotedKey(string source, ref int index, out string key) return "Could not find end of string value."; } var result = new string(buffer, 0, bufferIndex); - string escaped; - var errorMessage = result.EvaluateEscapeSequences(out escaped); + var errorMessage = result.EvaluateEscapeSequences(out string escaped); key = escaped; return errorMessage; } @@ -116,49 +115,43 @@ public static string GetSlices(this string source, ref int index, out IList= source.Length) - return "Expected ':', ',', or ']'."; + if (index >= source.Length) return "Expected ':', ',', or ']'."; if (n1.HasValue && source[index].In(',', ']')) { slice = new Slice(n1.Value); return null; } - if (source[index] != ':') - return "Expected ':', ',', or ']'."; + if (source[index] != ':') return "Expected ':', ',', or ']'."; index++; - error = GetInt(source, ref index, out n2); + error = _GetInt(source, ref index, out int? n2); if (error != null) return error; if (source[index].In(',', ']')) { slice = new Slice(n1, n2); return null; } - if (source[index] != ':') - return "Expected ':', ',', or ']'."; + if (source[index] != ':') return "Expected ':', ',', or ']'."; index++; - error = GetInt(source, ref index, out n3); + error = _GetInt(source, ref index, out int? n3); if (error != null) return error; if (source[index].In(',', ']')) { @@ -167,16 +160,15 @@ private static string GetSlice(this string source, ref int index, out Slice slic } return "Expected ',' or ']'."; } - public static string GetInt(string source, ref int index, out int? number) + private static string _GetInt(string source, ref int index, out int? number) { - int value; var text = new string(source.Substring(index).TakeWhile(c => char.IsDigit(c) || c == '-').ToArray()); if (text.Length == 0 && source[index].In(':', ',', ']')) { number = null; return null; } - if (!int.TryParse(text, out value)) + if (!int.TryParse(text, out int value)) { number = null; return "Expected number."; @@ -195,14 +187,13 @@ public static string GetInt(string source, ref int index, out int? number) public static string GetNumber(this string source, ref int index, out double? number) { - double value; var text = new string(source.Substring(index).TakeWhile(c => NumberChars.Contains(c)).ToArray()); if (text.Length == 0 && source[index].In(':', ',', ']')) { number = null; return null; } - if (!double.TryParse(text, out value)) + if (!double.TryParse(text, out double value)) { number = null; return "Expected number."; diff --git a/Manatee.Json/Path/Parsing/SearchIndexedArrayParser.cs b/Manatee.Json/Path/Parsing/SearchIndexedArrayParser.cs index a24811b..3e894d7 100644 --- a/Manatee.Json/Path/Parsing/SearchIndexedArrayParser.cs +++ b/Manatee.Json/Path/Parsing/SearchIndexedArrayParser.cs @@ -12,12 +12,11 @@ public bool Handles(string input) } public string TryParse(string source, ref int index, ref JsonPath path) { - if (path == null) - return "Start token not found."; + if (path == null) return "Start token not found."; index += 2; IList slices; - string error = source.GetSlices(ref index, out slices); + var error = source.GetSlices(ref index, out slices); if (error != null) return error; path = path.SearchArray(slices.ToArray()); diff --git a/Manatee.Json/Path/Parsing/SearchParser.cs b/Manatee.Json/Path/Parsing/SearchParser.cs index 94b8b9e..ac68bfc 100644 --- a/Manatee.Json/Path/Parsing/SearchParser.cs +++ b/Manatee.Json/Path/Parsing/SearchParser.cs @@ -10,8 +10,7 @@ public bool Handles(string input) } public string TryParse(string source, ref int index, ref JsonPath path) { - if (path == null) - return "Start token not found."; + if (path == null) return "Start token not found."; index += 2; diff --git a/Manatee.Json/Path/Parsing/StartParser.cs b/Manatee.Json/Path/Parsing/StartParser.cs index ab3f39d..60dec6d 100644 --- a/Manatee.Json/Path/Parsing/StartParser.cs +++ b/Manatee.Json/Path/Parsing/StartParser.cs @@ -8,8 +8,7 @@ public bool Handles(string input) } public string TryParse(string source, ref int index, ref JsonPath path) { - if (path != null) - return "Start token not valid in the middle of path."; + if (path != null) return "Start token not valid in the middle of path."; path = new JsonPath(); index++; diff --git a/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs b/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs index a6e67ef..358442d 100644 --- a/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs +++ b/Manatee.Json/Path/SearchParameters/NameSearchParameter.cs @@ -35,7 +35,7 @@ public IEnumerable Find(IEnumerable json, JsonValue root) } public override string ToString() { - return _name.Any(c => !char.IsLetterOrDigit(c)) || _name.IsNullOrWhiteSpace() + return _name.Any(c => !char.IsLetterOrDigit(c)) || string.IsNullOrWhiteSpace(_name) ? $"'{_name}'" : _name; } diff --git a/Manatee.Json/Path/Slice.cs b/Manatee.Json/Path/Slice.cs index ce27123..e5c28e4 100644 --- a/Manatee.Json/Path/Slice.cs +++ b/Manatee.Json/Path/Slice.cs @@ -99,8 +99,8 @@ internal IEnumerable Find(JsonArray json, JsonValue root) : new[] { json[Index.Value] }; } - var start = ResolveIndex(_start ?? 0, json.Count); - var end = ResolveIndex(_end ?? json.Count, json.Count); + var start = _ResolveIndex(_start ?? 0, json.Count); + var end = _ResolveIndex(_end ?? json.Count, json.Count); var step = Math.Max(_step ?? 1, 1); var index = start; @@ -113,7 +113,7 @@ internal IEnumerable Find(JsonArray json, JsonValue root) return list; } - private static int ResolveIndex(int index, int count) + private static int _ResolveIndex(int index, int count) { return index < 0 ? count + index : index; } diff --git a/Manatee.Json/Properties/AssemblyInfo.cs b/Manatee.Json/Properties/AssemblyInfo.cs index 2d0f8c5..024bab6 100644 --- a/Manatee.Json/Properties/AssemblyInfo.cs +++ b/Manatee.Json/Properties/AssemblyInfo.cs @@ -1,38 +1,3 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Manatee.Json")] -[assembly: AssemblyDescription("Provides an intuitive approach to building JSON structures.")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Little Crab Solutions")] -[assembly: AssemblyProduct("Manatee.Json")] -[assembly: AssemblyCopyright("Copyright © 2016 Little Crab Solutions")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("effb4352-e82d-445c-ba56-99a6d5ceb8b8")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("6.0.0.0")] -[assembly: AssemblyFileVersion("6.0.3")] +using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Manatee.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100bbe54aad91e473ca58d56672e66770435869a2388ac5a077457bf23b0872f5d656414709391f78751fd762ec25132d42ad60e319b821e37357964ac194b31a52e1d9772c507aed15527ff41564fdf85c7a90b09b7f8c8c321daf05404e7ccdaee0b5808db8aaa0ac2e8e3065509b5f1c75c4d1de5ceed995ae83fd36d10e8be0")] diff --git a/Manatee.Json/Schema/AdditionalItems.cs b/Manatee.Json/Schema/AdditionalItems.cs index f089146..973a0d1 100644 --- a/Manatee.Json/Schema/AdditionalItems.cs +++ b/Manatee.Json/Schema/AdditionalItems.cs @@ -1,7 +1,4 @@ using System; -#if !IOS && !CORE -using System.Data; -#endif using Manatee.Json.Serialization; namespace Manatee.Json.Schema @@ -68,8 +65,7 @@ public bool Equals(AdditionalItems other) /// The object to compare with the current object. 2 public override bool Equals(object obj) { - if (obj.GetType() != GetType()) return false; - return Equals(obj as AdditionalItems); + return obj.GetType() == GetType() && Equals(obj as AdditionalItems); } /// /// Serves as a hash function for a particular type. diff --git a/Manatee.Json/Schema/AdditionalProperties.cs b/Manatee.Json/Schema/AdditionalProperties.cs index 54e5f2b..68bd153 100644 --- a/Manatee.Json/Schema/AdditionalProperties.cs +++ b/Manatee.Json/Schema/AdditionalProperties.cs @@ -1,7 +1,4 @@ using System; -#if !IOS && !CORE -using System.Data; -#endif using Manatee.Json.Serialization; namespace Manatee.Json.Schema diff --git a/Manatee.Json/Schema/JsonSchema.cs b/Manatee.Json/Schema/JsonSchema.cs index 986ef95..ee95376 100644 --- a/Manatee.Json/Schema/JsonSchema.cs +++ b/Manatee.Json/Schema/JsonSchema.cs @@ -360,7 +360,7 @@ public string Id get { return _id; } set { - if (!value.IsNullOrWhiteSpace() && !StringFormat.Uri.Validate(value)) + if (!string.IsNullOrWhiteSpace(value) && !StringFormat.Uri.Validate(value)) throw new ArgumentOutOfRangeException(nameof(Id), "'id' property must be a well-formed URI."); _id = value; } @@ -376,7 +376,7 @@ public string Schema get { return _schema; } set { - if (!value.IsNullOrWhiteSpace() && !StringFormat.Uri.Validate(value)) + if (!string.IsNullOrWhiteSpace(value) && !StringFormat.Uri.Validate(value)) throw new ArgumentOutOfRangeException(nameof(Schema), "'$schema' property must be a well-formed URI."); _schema = value; } @@ -546,10 +546,9 @@ public virtual void FromJson(JsonValue json, JsonSerializer serializer) { var obj = json.Object; Id = obj.TryGetString("id"); - Uri uri; var uriFolder = DocumentPath?.OriginalString.EndsWith("/") ?? true ? DocumentPath : DocumentPath?.GetParentUri(); - if (!Id.IsNullOrWhiteSpace() && - (Uri.TryCreate(Id, UriKind.Absolute, out uri) || Uri.TryCreate(uriFolder + Id, UriKind.Absolute, out uri))) + if (!string.IsNullOrWhiteSpace(Id) && + (Uri.TryCreate(Id, UriKind.Absolute, out Uri uri) || Uri.TryCreate(uriFolder + Id, UriKind.Absolute, out uri))) { DocumentPath = uri; JsonSchemaRegistry.Register(this); @@ -661,7 +660,7 @@ public virtual void FromJson(JsonValue json, JsonSerializer serializer) { case JsonValueType.String: // string implies primitive type - Type = GetPrimitiveDefinition(typeEntry.String); + Type = _GetPrimitiveDefinition(typeEntry.String); break; case JsonValueType.Array: // array implies "oneOf" several primitive types @@ -699,9 +698,9 @@ public virtual JsonValue ToJson(JsonSerializer serializer) requiredProperties = Properties.Where(p => p.IsRequired).Select(p => p.Name).ToList(); var json = new JsonObject(); if (Id != null) json["id"] = Id; - if (!Schema.IsNullOrWhiteSpace()) json["$schema"] = Schema; + if (!string.IsNullOrWhiteSpace(Schema)) json["$schema"] = Schema; if (Title != null) json["title"] = Title; - if (!Description.IsNullOrWhiteSpace()) json["description"] = Description; + if (!string.IsNullOrWhiteSpace(Description)) json["description"] = Description; if (Default != null) json["default"] = Default; if (MultipleOf.HasValue) json["multipleOf"] = MultipleOf; if (Maximum.HasValue) json["maximum"] = Maximum; @@ -716,8 +715,7 @@ public virtual JsonValue ToJson(JsonSerializer serializer) if (Items != null) { var items = Items as JsonSchema; - var type = items?.Type as JsonSchemaMultiTypeDefinition; - if (type != null && !type.IsPrimitive) + if (items?.Type is JsonSchemaMultiTypeDefinition type && !type.IsPrimitive) json["items"] = items.Type.ToJson(serializer); else json["items"] = Items.ToJson(serializer); @@ -865,7 +863,7 @@ public override int GetHashCode() } } - private static JsonSchemaTypeDefinition GetPrimitiveDefinition(string type) + private static JsonSchemaTypeDefinition _GetPrimitiveDefinition(string type) { switch (type) { diff --git a/Manatee.Json/Schema/JsonSchemaFactory.cs b/Manatee.Json/Schema/JsonSchemaFactory.cs index cba0f3d..8579877 100644 --- a/Manatee.Json/Schema/JsonSchemaFactory.cs +++ b/Manatee.Json/Schema/JsonSchemaFactory.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Manatee.Json.Internal; namespace Manatee.Json.Schema { @@ -64,6 +63,7 @@ public static IJsonSchema FromJson(JsonValue json, Uri documentPath = null) return schema; } +#if !NETSTANDARD1_3 /// /// Builds a implementation which can validate JSON for a given type. /// @@ -131,5 +131,6 @@ private static IJsonSchema GetBasicSchema(Type type) return new JsonSchema {Type = JsonSchemaTypeDefinition.Number}; return null; } +#endif } } \ No newline at end of file diff --git a/Manatee.Json/Schema/JsonSchemaMultiTypeDefinition.cs b/Manatee.Json/Schema/JsonSchemaMultiTypeDefinition.cs index f5c32e4..12ef141 100644 --- a/Manatee.Json/Schema/JsonSchemaMultiTypeDefinition.cs +++ b/Manatee.Json/Schema/JsonSchemaMultiTypeDefinition.cs @@ -12,9 +12,8 @@ namespace Manatee.Json.Schema public class JsonSchemaMultiTypeDefinition : JsonSchemaTypeDefinition { private readonly bool _nonPrimitiveAllowed; - private IEnumerable _definitions; - internal IEnumerable Defintions => _definitions; + internal IEnumerable Defintions { get; private set; } internal bool IsPrimitive => !_nonPrimitiveAllowed; /// @@ -23,12 +22,12 @@ public class JsonSchemaMultiTypeDefinition : JsonSchemaTypeDefinition public JsonSchemaMultiTypeDefinition(params JsonSchemaTypeDefinition[] definitions) : this(false) { - _definitions = definitions.ToList(); + Defintions = definitions.ToList(); - if (_definitions.Except(PrimitiveDefinitions).Any()) + if (Defintions.Except(PrimitiveDefinitions).Any()) throw new InvalidOperationException("Only primitive types are allowed in type collections."); - Definition = new JsonSchema { OneOf = _definitions.Select(d => d.Definition) }; + Definition = new JsonSchema { OneOf = Defintions.Select(d => d.Definition) }; } internal JsonSchemaMultiTypeDefinition(bool nonPrimitiveAllowed) { @@ -44,7 +43,7 @@ internal JsonSchemaMultiTypeDefinition(bool nonPrimitiveAllowed) public override void FromJson(JsonValue json, JsonSerializer serializer) { var typeEntry = json.Array; - _definitions = typeEntry.Select(jv => + Defintions = typeEntry.Select(jv => { if (_nonPrimitiveAllowed) return new JsonSchemaTypeDefinition(JsonSchemaFactory.FromJson(jv)); var definition = PrimitiveDefinitions.FirstOrDefault(p => p.Name == jv.String); @@ -53,7 +52,7 @@ public override void FromJson(JsonValue json, JsonSerializer serializer) return definition; }).ToList(); - Definition = new JsonSchema {OneOf = _definitions.Select(d => d.Definition)}; } + Definition = new JsonSchema {OneOf = Defintions.Select(d => d.Definition)}; } /// /// Converts an object to a . /// @@ -62,7 +61,7 @@ public override void FromJson(JsonValue json, JsonSerializer serializer) /// The representation of the object. public override JsonValue ToJson(JsonSerializer serializer) { - return _definitions.ToJson(serializer); + return Defintions.ToJson(serializer); } /// /// Determines whether the specified is equal to the current . @@ -89,13 +88,13 @@ public override int GetHashCode() { unchecked { - return (base.GetHashCode()*397) ^ (_definitions?.GetCollectionHashCode() ?? 0); + return (base.GetHashCode()*397) ^ (Defintions?.GetCollectionHashCode() ?? 0); } } private bool Equals(JsonSchemaMultiTypeDefinition other) { - return base.Equals(other) && _definitions.ContentsEqual(other._definitions); + return base.Equals(other) && Defintions.ContentsEqual(other.Defintions); } } } \ No newline at end of file diff --git a/Manatee.Json/Schema/JsonSchemaOptions.cs b/Manatee.Json/Schema/JsonSchemaOptions.cs index 3b6f3a3..05de557 100644 --- a/Manatee.Json/Schema/JsonSchemaOptions.cs +++ b/Manatee.Json/Schema/JsonSchemaOptions.cs @@ -1,9 +1,6 @@ using System; -using System.Net; -#if IOS || CORE +using System.IO; using System.Net.Http; -#endif -using System.Text; namespace Manatee.Json.Schema { @@ -19,11 +16,7 @@ public static class JsonSchemaOptions /// public static Func Download { -#if IOS || CORE - get { return _download ?? (_download = uri => new HttpClient().GetStringAsync(uri).Result); } -#else - get { return _download ?? (_download = uri => new WebClient {Encoding = Encoding.UTF8}.DownloadString(uri)); } -#endif + get { return _download ?? (_download = _BasicDownload); } set { _download = value; } } @@ -39,5 +32,22 @@ static JsonSchemaOptions() { ValidateFormat = true; } + + private static string _BasicDownload(string path) + { + var uri = new Uri(path); + + switch (uri.Scheme) + { + case "http": + case "https:": + return new HttpClient().GetStringAsync(uri).Result; + case "file": + var filename = Uri.UnescapeDataString(uri.AbsolutePath); + return File.ReadAllText(filename); + default: + throw new Exception(); + } + } } } diff --git a/Manatee.Json/Schema/JsonSchemaPropertyDefinition.cs b/Manatee.Json/Schema/JsonSchemaPropertyDefinition.cs index 68750e8..ba72123 100644 --- a/Manatee.Json/Schema/JsonSchemaPropertyDefinition.cs +++ b/Manatee.Json/Schema/JsonSchemaPropertyDefinition.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using Manatee.Json.Internal; using Manatee.Json.Serialization; namespace Manatee.Json.Schema @@ -35,7 +34,7 @@ public class JsonSchemaPropertyDefinition : IJsonSerializable, IEquatableThrown if is null, empty, or whitespace. public JsonSchemaPropertyDefinition(string name) { - if (name.IsNullOrWhiteSpace()) + if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name)); Name = name; diff --git a/Manatee.Json/Schema/JsonSchemaReference.cs b/Manatee.Json/Schema/JsonSchemaReference.cs index 4a6cb34..1dfb7ea 100644 --- a/Manatee.Json/Schema/JsonSchemaReference.cs +++ b/Manatee.Json/Schema/JsonSchemaReference.cs @@ -1,10 +1,7 @@ using System; -using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; -using Manatee.Json.Internal; -using Manatee.Json.Path; using Manatee.Json.Serialization; namespace Manatee.Json.Schema @@ -42,7 +39,7 @@ public class JsonSchemaReference : JsonSchema /// Thrown when is nulll, empty, or whitespace. public JsonSchemaReference(string reference) { - if (reference.IsNullOrWhiteSpace()) throw new ArgumentNullException(nameof(reference)); + if (string.IsNullOrWhiteSpace(reference)) throw new ArgumentNullException(nameof(reference)); Reference = reference; } /// @@ -111,13 +108,12 @@ public override int GetHashCode() private JsonValue _Resolve(JsonValue root) { var referenceParts = Reference.Split(new[] { '#' }, StringSplitOptions.None); - var address = referenceParts[0].IsNullOrWhiteSpace() ? DocumentPath?.OriginalString : referenceParts[0]; + var address = string.IsNullOrWhiteSpace(referenceParts[0]) ? DocumentPath?.OriginalString : referenceParts[0]; var fragment = referenceParts.Length > 1 ? referenceParts[1] : string.Empty; var jValue = root; - if (!address.IsNullOrWhiteSpace()) + if (!string.IsNullOrWhiteSpace(address)) { - Uri absolute; - if (!Uri.TryCreate(address, UriKind.Absolute, out absolute)) + if (!Uri.TryCreate(address, UriKind.Absolute, out Uri absolute)) { address = Id + address; } @@ -132,7 +128,7 @@ private JsonValue _Resolve(JsonValue root) if (jValue == null) return root; if (jValue == _rootJson) throw new ArgumentException("Cannot use a root reference as the base schema."); - Resolved = _ResolveLocalReference(jValue, fragment, address.IsNullOrWhiteSpace() ? null : new Uri(address)); + Resolved = _ResolveLocalReference(jValue, fragment, string.IsNullOrWhiteSpace(address) ? null : new Uri(address)); return jValue; } private static IJsonSchema _ResolveLocalReference(JsonValue root, string path, Uri documentPath) @@ -146,11 +142,9 @@ private static IJsonSchema _ResolveLocalReference(JsonValue root, string path, U if (value.Type == JsonValueType.Object) { if (!value.Object.ContainsKey(unescaped)) return null; - JsonValue id; - if (value.Object.TryGetValue("id", out id)) + if (value.Object.TryGetValue("id", out JsonValue id)) { - Uri uri; - documentPath = Uri.TryCreate(id.String, UriKind.Absolute, out uri) + documentPath = Uri.TryCreate(id.String, UriKind.Absolute, out Uri uri) ? uri : new Uri(documentPath, id.String); } @@ -158,8 +152,7 @@ private static IJsonSchema _ResolveLocalReference(JsonValue root, string path, U } else if (value.Type == JsonValueType.Array) { - int index; - if (!int.TryParse(unescaped, out index) || index >= value.Array.Count) return null; + if (!int.TryParse(unescaped, out int index) || index >= value.Array.Count) return null; value = value.Array[index]; } } diff --git a/Manatee.Json/Schema/JsonSchemaRegistry.cs b/Manatee.Json/Schema/JsonSchemaRegistry.cs index c8807dd..ea85232 100644 --- a/Manatee.Json/Schema/JsonSchemaRegistry.cs +++ b/Manatee.Json/Schema/JsonSchemaRegistry.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; namespace Manatee.Json.Schema { @@ -43,7 +42,7 @@ public static IJsonSchema Get(string uri) if (!validation.Valid) { - var errors = validation.Errors.Select(e => e.Message).Join(Environment.NewLine); + var errors = string.Join(Environment.NewLine, validation.Errors.Select(e => e.Message)); throw new ArgumentException($"The given path does not contain a valid schema. Errors: \n{errors}"); } @@ -59,7 +58,7 @@ public static IJsonSchema Get(string uri) /// public static void Register(JsonSchema schema) { - if (schema.Id.IsNullOrWhiteSpace()) return; + if (string.IsNullOrWhiteSpace(schema.Id)) return; lock (_schemaLookup) { _schemaLookup[schema.DocumentPath.ToString()] = schema; @@ -71,7 +70,7 @@ public static void Register(JsonSchema schema) /// public static void Unregister(JsonSchema schema) { - if (schema.Id.IsNullOrWhiteSpace()) return; + if (string.IsNullOrWhiteSpace(schema.Id)) return; lock (_schemaLookup) { _schemaLookup.Remove(schema.Id); @@ -83,7 +82,7 @@ public static void Unregister(JsonSchema schema) /// public static void Unregister(string uri) { - if (uri.IsNullOrWhiteSpace()) return; + if (string.IsNullOrWhiteSpace(uri)) return; lock (_schemaLookup) { _schemaLookup.Remove(uri); diff --git a/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs b/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs index d5fb551..acd7e3d 100644 --- a/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs +++ b/Manatee.Json/Schema/JsonSchemaTypeDefinition.cs @@ -1,10 +1,6 @@ using System; using System.Collections.Generic; -#if !IOS && !CORE -using System.Data; -#endif using System.Linq; -using Manatee.Json.Internal; using Manatee.Json.Serialization; namespace Manatee.Json.Schema @@ -101,8 +97,7 @@ static JsonSchemaTypeDefinition() /// Thrown if is null, empty, or whitespace. public JsonSchemaTypeDefinition(string name) { - if (name.IsNullOrWhiteSpace()) - throw new ArgumentNullException(nameof(name)); + if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name)); Name = name; } @@ -136,7 +131,7 @@ public virtual void FromJson(JsonValue json, JsonSerializer serializer) /// 2 public override string ToString() { - if (!Name.IsNullOrWhiteSpace()) return Name; + if (!string.IsNullOrWhiteSpace(Name)) return Name; return ToJson(null).ToString(); } diff --git a/Manatee.Json/Schema/PropertyDependency.cs b/Manatee.Json/Schema/PropertyDependency.cs index db6dc05..5ad8347 100644 --- a/Manatee.Json/Schema/PropertyDependency.cs +++ b/Manatee.Json/Schema/PropertyDependency.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; namespace Manatee.Json.Schema { @@ -25,7 +24,7 @@ public class PropertyDependency : IJsonSchemaDependency public PropertyDependency(string propertyName, IEnumerable dependencies) { if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); - if (propertyName.IsNullOrWhiteSpace()) throw new ArgumentException("Must provide a property name."); + if (string.IsNullOrWhiteSpace(propertyName)) throw new ArgumentException("Must provide a property name."); if (dependencies == null) throw new ArgumentNullException(nameof(dependencies)); if (!dependencies.Any()) throw new ArgumentException("Cannot create property dependency on no properties."); diff --git a/Manatee.Json/Schema/SchemaDependency.cs b/Manatee.Json/Schema/SchemaDependency.cs index 036fe71..6b453c3 100644 --- a/Manatee.Json/Schema/SchemaDependency.cs +++ b/Manatee.Json/Schema/SchemaDependency.cs @@ -1,5 +1,4 @@ using System; -using Manatee.Json.Internal; namespace Manatee.Json.Schema { @@ -24,7 +23,7 @@ public SchemaDependency(string propertyName, IJsonSchema schema) { _schema = schema; if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); - if (propertyName.IsNullOrWhiteSpace()) throw new ArgumentException("Must provide a property name."); + if (string.IsNullOrWhiteSpace(propertyName)) throw new ArgumentException("Must provide a property name."); PropertyName = propertyName; } diff --git a/Manatee.Json/Schema/SchemaValidationError.cs b/Manatee.Json/Schema/SchemaValidationError.cs index d24940b..f115112 100644 --- a/Manatee.Json/Schema/SchemaValidationError.cs +++ b/Manatee.Json/Schema/SchemaValidationError.cs @@ -1,5 +1,4 @@ using System; -using Manatee.Json.Internal; namespace Manatee.Json.Schema { @@ -25,7 +24,7 @@ internal SchemaValidationError(string propertyName, string message) internal SchemaValidationError PrependPropertyName(string parent) { - if (PropertyName.IsNullOrWhiteSpace()) + if (string.IsNullOrWhiteSpace(PropertyName)) PropertyName = parent; else PropertyName = parent + (PropertyName[0] == '[' ? string.Empty : ".") + PropertyName; @@ -41,7 +40,7 @@ internal SchemaValidationError PrependPropertyName(string parent) /// 2 public override string ToString() { - return PropertyName.IsNullOrWhiteSpace() + return string.IsNullOrWhiteSpace(PropertyName) ? Message : $"Property: {PropertyName} - {Message}"; } diff --git a/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs b/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs index 18ffac8..a4e3f70 100644 --- a/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs +++ b/Manatee.Json/Schema/Validators/JsonSchemaPropertyValidatorFactory.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Schema.Validators { @@ -11,11 +11,11 @@ internal static class JsonSchemaPropertyValidatorFactory static JsonSchemaPropertyValidatorFactory() { - AllValidators = typeof(IJsonSchemaPropertyValidator).TypeInfo().Assembly.GetTypes() - .Where(t => typeof(IJsonSchemaPropertyValidator).IsAssignableFrom(t) && - !t.TypeInfo().IsAbstract && - t.TypeInfo().IsClass) - .Select(Activator.CreateInstance) + AllValidators = typeof(IJsonSchemaPropertyValidator).GetTypeInfo().Assembly.DefinedTypes + .Where(t => typeof(IJsonSchemaPropertyValidator).GetTypeInfo().IsAssignableFrom(t) && + !t.IsAbstract && + t.IsClass) + .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() .ToList(); } diff --git a/Manatee.Json/Schema/Validators/MaxPropertySchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/MaxPropertySchemaPropertyValidator.cs index d68a3a9..e7ab7d0 100644 --- a/Manatee.Json/Schema/Validators/MaxPropertySchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/MaxPropertySchemaPropertyValidator.cs @@ -8,9 +8,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if (json.Object.Count > schema.MaxProperties) - return new SchemaValidationResults(string.Empty, $"Expected: <= {schema.MaxProperties} properties; Actual: {json.Object.Count} properties."); - return new SchemaValidationResults(); + return json.Object.Count > schema.MaxProperties + ? new SchemaValidationResults(string.Empty, $"Expected: <= {schema.MaxProperties} properties; Actual: {json.Object.Count} properties.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Schema/Validators/MinItemsSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/MinItemsSchemaPropertyValidator.cs index 070fb62..6fffc08 100644 --- a/Manatee.Json/Schema/Validators/MinItemsSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/MinItemsSchemaPropertyValidator.cs @@ -8,9 +8,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if (json.Array.Count < schema.MinItems) - return new SchemaValidationResults(string.Empty, $"Expected: >= {schema.MinItems} items; Actual: {json.Array.Count} items."); - return new SchemaValidationResults(); + return json.Array.Count < schema.MinItems + ? new SchemaValidationResults(string.Empty, $"Expected: >= {schema.MinItems} items; Actual: {json.Array.Count} items.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Schema/Validators/MinLengthSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/MinLengthSchemaPropertyValidator.cs index 7fbf0c8..243882c 100644 --- a/Manatee.Json/Schema/Validators/MinLengthSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/MinLengthSchemaPropertyValidator.cs @@ -11,7 +11,7 @@ public bool Applies(JsonSchema schema, JsonValue json) public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { var length = new StringInfo(json.String).LengthInTextElements; - if (schema.MinLength.HasValue && (length < schema.MinLength)) + if (schema.MinLength.HasValue && length < schema.MinLength) return new SchemaValidationResults(string.Empty, $"Expected: length >= {schema.MinLength}; Actual: {length}."); return new SchemaValidationResults(); } diff --git a/Manatee.Json/Schema/Validators/MinPropertiesSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/MinPropertiesSchemaPropertyValidator.cs index c79e667..8a44b0b 100644 --- a/Manatee.Json/Schema/Validators/MinPropertiesSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/MinPropertiesSchemaPropertyValidator.cs @@ -8,9 +8,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if (json.Object.Count < schema.MinProperties) - return new SchemaValidationResults(string.Empty, $"Expected: >= {schema.MinProperties} items; Actual: {json.Object.Count} items."); - return new SchemaValidationResults(); + return json.Object.Count < schema.MinProperties + ? new SchemaValidationResults(string.Empty, $"Expected: >= {schema.MinProperties} items; Actual: {json.Object.Count} items.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Schema/Validators/MultipleOfSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/MultipleOfSchemaPropertyValidator.cs index aede343..3762e70 100644 --- a/Manatee.Json/Schema/Validators/MultipleOfSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/MultipleOfSchemaPropertyValidator.cs @@ -8,9 +8,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if ((decimal) json.Number%(decimal) schema.MultipleOf.Value != 0) - return new SchemaValidationResults(string.Empty, $"Expected: {json.Number}%{schema.MultipleOf}=0; Actual: {json.Number%schema.MultipleOf}."); - return new SchemaValidationResults(); + return (decimal) json.Number % (decimal?) schema.MultipleOf != 0 + ? new SchemaValidationResults(string.Empty, $"Expected: {json.Number}%{schema.MultipleOf}=0; Actual: {json.Number % schema.MultipleOf}.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Schema/Validators/NotSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/NotSchemaPropertyValidator.cs index d41fb1f..f417304 100644 --- a/Manatee.Json/Schema/Validators/NotSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/NotSchemaPropertyValidator.cs @@ -9,9 +9,9 @@ public bool Applies(JsonSchema schema, JsonValue json) public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { var results = schema.Not.Validate(json, root); - if (results.Valid) - return new SchemaValidationResults(string.Empty, "Expected schema to be invalid, but was valid."); - return new SchemaValidationResults(); + return results.Valid + ? new SchemaValidationResults(string.Empty, "Expected schema to be invalid, but was valid.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Schema/Validators/PatternSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/PatternSchemaPropertyValidator.cs index 947dfac..9016224 100644 --- a/Manatee.Json/Schema/Validators/PatternSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/PatternSchemaPropertyValidator.cs @@ -10,9 +10,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if (!Regex.IsMatch(json.String, schema.Pattern)) - return new SchemaValidationResults(string.Empty, $"Value [{json.String}] does not match required Regex pattern [{schema.Pattern}]."); - return new SchemaValidationResults(); + return Regex.IsMatch(json.String, schema.Pattern) + ? new SchemaValidationResults() + : new SchemaValidationResults(string.Empty, $"Value [{json.String}] does not match required Regex pattern [{schema.Pattern}]."); } } } diff --git a/Manatee.Json/Schema/Validators/UniqueItemsSchemaPropertyValidator.cs b/Manatee.Json/Schema/Validators/UniqueItemsSchemaPropertyValidator.cs index 3a9a128..18bc1d1 100644 --- a/Manatee.Json/Schema/Validators/UniqueItemsSchemaPropertyValidator.cs +++ b/Manatee.Json/Schema/Validators/UniqueItemsSchemaPropertyValidator.cs @@ -10,9 +10,9 @@ public bool Applies(JsonSchema schema, JsonValue json) } public SchemaValidationResults Validate(JsonSchema schema, JsonValue json, JsonValue root) { - if (json.Array.Count != json.Array.Distinct().Count()) - return new SchemaValidationResults(string.Empty, "Expected unique items; Duplicates were found."); - return new SchemaValidationResults(); + return json.Array.Count != json.Array.Distinct().Count() + ? new SchemaValidationResults(string.Empty, "Expected unique items; Duplicates were found.") + : new SchemaValidationResults(); } } } diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/ArraySerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/ArraySerializationDelegateProvider.cs index dd60c52..7b894e0 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/ArraySerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/ArraySerializationDelegateProvider.cs @@ -16,13 +16,13 @@ protected override Type[] GetTypeArguments(Type type) return new[] { type.GetElementType() }; } - private static JsonValue Encode(T[] array, JsonSerializer serializer) + private static JsonValue _Encode(T[] array, JsonSerializer serializer) { var json = new JsonArray(); json.AddRange(array.Select(serializer.Serialize)); return json; } - private static T[] Decode(JsonValue json, JsonSerializer serializer) + private static T[] _Decode(JsonValue json, JsonSerializer serializer) { var list = new List(); list.AddRange(json.Array.Select(serializer.Deserialize)); diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/DateTimeSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/DateTimeSerializationDelegateProvider.cs index 3b9fe12..09f359f 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/DateTimeSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/DateTimeSerializationDelegateProvider.cs @@ -10,7 +10,7 @@ public override bool CanHandle(Type type) return type == typeof(DateTime); } - private static JsonValue Encode(DateTime dt, JsonSerializer serializer) + private static JsonValue _Encode(DateTime dt, JsonSerializer serializer) { if (serializer.Options == null) return dt.ToString(); @@ -28,7 +28,7 @@ private static JsonValue Encode(DateTime dt, JsonSerializer serializer) throw new ArgumentOutOfRangeException(); } } - private static DateTime Decode(JsonValue json, JsonSerializer serializer) + private static DateTime _Decode(JsonValue json, JsonSerializer serializer) { if (serializer.Options == null) return DateTime.Parse(json.String); diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs index b24744c..8cd8640 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/DictionarySerializationDelegateProvider.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { @@ -9,10 +9,10 @@ internal class DictionarySerializationDelegateProvider : SerializationDelegatePr { public override bool CanHandle(Type type) { - return type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>); } - private static JsonValue Encode(Dictionary dict, JsonSerializer serializer) + private static JsonValue _Encode(Dictionary dict, JsonSerializer serializer) { var array = new JsonArray(); array.AddRange(dict.Select(item => (JsonValue)(new JsonObject @@ -22,7 +22,7 @@ public override bool CanHandle(Type type) }))); return array; } - private static Dictionary Decode(JsonValue json, JsonSerializer serializer) + private static Dictionary _Decode(JsonValue json, JsonSerializer serializer) { return json.Array.ToDictionary(jv => serializer.Deserialize(jv.Object["Key"]), jv => serializer.Deserialize(jv.Object["Value"])); diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/GuidSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/GuidSerializationDelegateProvider.cs index 2e98a3b..26ef21b 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/GuidSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/GuidSerializationDelegateProvider.cs @@ -9,11 +9,11 @@ public override bool CanHandle(Type type) return type == typeof(Guid); } - private static JsonValue Encode(Guid guid, JsonSerializer serializer) + private static JsonValue _Encode(Guid guid, JsonSerializer serializer) { return guid.ToString(); } - private static Guid Decode(JsonValue json, JsonSerializer serializer) + private static Guid _Decode(JsonValue json, JsonSerializer serializer) { return json.Type == JsonValueType.String ? new Guid(json.String) : default(Guid); } diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs index 7be61a6..c97ed16 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/ListSerializationDelegateProvider.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { @@ -9,16 +9,16 @@ internal class ListSerializationDelegateProvider : SerializationDelegateProvider { public override bool CanHandle(Type type) { - return type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>); } - private static JsonValue Encode(List list, JsonSerializer serializer) + private static JsonValue _Encode(List list, JsonSerializer serializer) { var array = new JsonArray(); array.AddRange(list.Select(serializer.Serialize)); return array; } - private static List Decode(JsonValue json, JsonSerializer serializer) + private static List _Decode(JsonValue json, JsonSerializer serializer) { var list = new List(); list.AddRange(json.Array.Select(serializer.Deserialize)); diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs index 1cd3ec2..008d0ce 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/NullableSerializationDelegateProvider.cs @@ -1,5 +1,5 @@ using System; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { @@ -7,10 +7,10 @@ internal class NullableSerializationDelegateProvider : SerializationDelegateProv { public override bool CanHandle(Type type) { - return type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } - private static JsonValue Encode(T? nullable, JsonSerializer serializer) + private static JsonValue _Encode(T? nullable, JsonSerializer serializer) where T : struct { if (!nullable.HasValue) return JsonValue.Null; @@ -20,7 +20,7 @@ private static JsonValue Encode(T? nullable, JsonSerializer serializer) serializer.Options.EncodeDefaultValues = encodeDefaultValues; return json; } - private static T? Decode(JsonValue json, JsonSerializer serializer) + private static T? _Decode(JsonValue json, JsonSerializer serializer) where T : struct { if (json == JsonValue.Null) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs index 18ca92a..6596fb3 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/QueueSerializationDelegateProvider.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { @@ -9,10 +9,10 @@ internal class QueueSerializationDelegateProvider : SerializationDelegateProvide { public override bool CanHandle(Type type) { - return type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Queue<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Queue<>); } - private static JsonValue Encode(Queue queue, JsonSerializer serializer) + private static JsonValue _Encode(Queue queue, JsonSerializer serializer) { var array = new JsonArray(); for (int i = 0; i < queue.Count; i++) @@ -21,7 +21,7 @@ private static JsonValue Encode(Queue queue, JsonSerializer serializer) } return array; } - private static Queue Decode(JsonValue json, JsonSerializer serializer) + private static Queue _Decode(JsonValue json, JsonSerializer serializer) { var queue = new Queue(); for (int i = 0; i < json.Array.Count; i++) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs index 7903e33..d867d4b 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/SerializationDelegateProviderBase.cs @@ -11,13 +11,8 @@ internal abstract class SerializationDelegateProviderBase : ISerializationDelega protected SerializationDelegateProviderBase() { -#if !IOS - _encodeMethod = GetType().GetMethod("Encode", BindingFlags.NonPublic | BindingFlags.Static); - _decodeMethod = GetType().GetMethod("Decode", BindingFlags.NonPublic | BindingFlags.Static); -#else - _encodeMethod = GetType().TypeInfo().GetDeclaredMethod("Encode"); - _decodeMethod = GetType().TypeInfo().GetDeclaredMethod("Decode"); -#endif + _encodeMethod = GetType().GetTypeInfo().GetDeclaredMethod("_Encode"); + _decodeMethod = GetType().GetTypeInfo().GetDeclaredMethod("_Decode"); } public abstract bool CanHandle(Type type); @@ -27,11 +22,7 @@ public JsonSerializationTypeRegistry.ToJsonDelegate GetEncoder() var toJson = _encodeMethod; if (toJson.IsGenericMethod) toJson = toJson.MakeGenericMethod(typeArguments); -#if IOS || CORE - return (JsonSerializationTypeRegistry.ToJsonDelegate) toJson.CreateDelegate(typeof (JsonSerializationTypeRegistry.ToJsonDelegate), toJson); -#else - return (JsonSerializationTypeRegistry.ToJsonDelegate) Delegate.CreateDelegate(typeof (JsonSerializationTypeRegistry.ToJsonDelegate), toJson); -#endif + return (JsonSerializationTypeRegistry.ToJsonDelegate) toJson.CreateDelegate(typeof (JsonSerializationTypeRegistry.ToJsonDelegate), null); } public JsonSerializationTypeRegistry.FromJsonDelegate GetDecoder() { @@ -39,11 +30,7 @@ public JsonSerializationTypeRegistry.FromJsonDelegate GetDecoder() var fromJson = _decodeMethod; if (fromJson.IsGenericMethod) fromJson = fromJson.MakeGenericMethod(typeArguments); -#if IOS || CORE - return (JsonSerializationTypeRegistry.FromJsonDelegate) fromJson.CreateDelegate(typeof(JsonSerializationTypeRegistry.FromJsonDelegate), fromJson); -#else - return (JsonSerializationTypeRegistry.FromJsonDelegate) Delegate.CreateDelegate(typeof (JsonSerializationTypeRegistry.FromJsonDelegate), fromJson); -#endif + return (JsonSerializationTypeRegistry.FromJsonDelegate) fromJson.CreateDelegate(typeof(JsonSerializationTypeRegistry.FromJsonDelegate), null); } protected virtual Type[] GetTypeArguments(Type type) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs index dfabab3..2991b6e 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/StackSerializationDelegateProvider.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using Manatee.Json.Internal; +using System.Reflection; namespace Manatee.Json.Serialization.Internal.AutoRegistration { @@ -9,10 +9,10 @@ internal class StackSerializationDelegateProvider : SerializationDelegateProvide { public override bool CanHandle(Type type) { - return type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Stack<>); } - private static JsonValue Encode(Stack stack, JsonSerializer serializer) + private static JsonValue _Encode(Stack stack, JsonSerializer serializer) { var array = new JsonArray(); for (int i = 0; i < stack.Count; i++) @@ -21,7 +21,7 @@ private static JsonValue Encode(Stack stack, JsonSerializer serializer) } return array; } - private static Stack Decode(JsonValue json, JsonSerializer serializer) + private static Stack _Decode(JsonValue json, JsonSerializer serializer) { var stack = new Stack(); for (int i = 0; i < json.Array.Count; i++) diff --git a/Manatee.Json/Serialization/Internal/AutoRegistration/TimeSpanSerializationDelegateProvider.cs b/Manatee.Json/Serialization/Internal/AutoRegistration/TimeSpanSerializationDelegateProvider.cs index 158df07..62a1585 100644 --- a/Manatee.Json/Serialization/Internal/AutoRegistration/TimeSpanSerializationDelegateProvider.cs +++ b/Manatee.Json/Serialization/Internal/AutoRegistration/TimeSpanSerializationDelegateProvider.cs @@ -9,11 +9,11 @@ public override bool CanHandle(Type type) return type == typeof(TimeSpan); } - private static JsonValue Encode(TimeSpan ts, JsonSerializer serializer) + private static JsonValue _Encode(TimeSpan ts, JsonSerializer serializer) { return ts.ToString(); } - private static TimeSpan Decode(JsonValue json, JsonSerializer serializer) + private static TimeSpan _Decode(JsonValue json, JsonSerializer serializer) { return json.Type == JsonValueType.String ? TimeSpan.Parse(json.String) : default(TimeSpan); } diff --git a/Manatee.Json/Serialization/Internal/ConstructorResolver.cs b/Manatee.Json/Serialization/Internal/ConstructorResolver.cs index d9b3ab6..fe2fea0 100644 --- a/Manatee.Json/Serialization/Internal/ConstructorResolver.cs +++ b/Manatee.Json/Serialization/Internal/ConstructorResolver.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Reflection; -using Manatee.Json.Internal; namespace Manatee.Json.Serialization.Internal { @@ -15,17 +14,13 @@ public object Resolve(Type type) { try { -#if IOS - var constructors = type.TypeInfo().DeclaredConstructors.ToList(); -#else - var constructors = type.TypeInfo().GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).ToList(); -#endif + var constructors = type.GetTypeInfo().DeclaredConstructors.ToList(); if (!constructors.Any()) return Activator.CreateInstance(type); var parameterless = constructors.FirstOrDefault(c => !c.GetParameters().Any()); if (parameterless != null) return parameterless.Invoke(null); - var constructor = constructors.OrderBy(c => c.GetParameters().Count()).First(); + var constructor = constructors.OrderBy(c => c.GetParameters().Length).First(); var parameters = constructor.GetParameters().Select(p => Resolve(p.ParameterType)).ToArray(); return constructor.Invoke(parameters); } diff --git a/Manatee.Json/Serialization/Internal/SerializerCache.cs b/Manatee.Json/Serialization/Internal/SerializerCache.cs index 3a50ed4..37679b2 100644 --- a/Manatee.Json/Serialization/Internal/SerializerCache.cs +++ b/Manatee.Json/Serialization/Internal/SerializerCache.cs @@ -1,35 +1,31 @@ using System; -#if !NET35 && !IOS -using Dictionary = System.Collections.Concurrent.ConcurrentDictionary; -#else -using Dictionary = System.Collections.Generic.Dictionary; -#endif +using System.Collections.Generic; using System.Reflection; namespace Manatee.Json.Serialization.Internal { internal static class SerializerCache { - private static readonly Dictionary _cache; + private static readonly Dictionary _cache; static SerializerCache() { - _cache = new Dictionary(); + _cache = new Dictionary(); } public static MethodInfo GetSerializeMethod(Type type) { - var pair = EnsureMethodPair(type); + var pair = _EnsureMethodPair(type); return pair.Serializer; } public static MethodInfo GetDeserializeMethod(Type type) { - var pair = EnsureMethodPair(type); + var pair = _EnsureMethodPair(type); return pair.Deserializer; } - private static SerializerMethodPair EnsureMethodPair(Type type) + private static SerializerMethodPair _EnsureMethodPair(Type type) { SerializerMethodPair pair; if (!_cache.TryGetValue(type, out pair)) diff --git a/Manatee.Json/Serialization/Internal/SerializerFactory.cs b/Manatee.Json/Serialization/Internal/SerializerFactory.cs index 897561d..10bfb83 100644 --- a/Manatee.Json/Serialization/Internal/SerializerFactory.cs +++ b/Manatee.Json/Serialization/Internal/SerializerFactory.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Reflection; using Manatee.Json.Internal; using Manatee.Json.Schema; using Manatee.Json.Serialization.Internal.Serializers; @@ -53,42 +54,43 @@ public static ISerializer GetSerializer(JsonSerializerOptions options, JsonVa { var type = typeof (T); var typeToSerialize = JsonSerializationAbstractionMap.GetMap(type); - if (typeof (IJsonSchema).IsAssignableFrom(typeToSerialize)) - return BuildSerializer(_schemaSerializer); + var typeInfo = typeToSerialize.GetTypeInfo(); + if (typeof (IJsonSchema).GetTypeInfo().IsAssignableFrom(typeInfo)) + return _BuildSerializer(_schemaSerializer); if (JsonSerializationTypeRegistry.IsRegistered(typeToSerialize)) - return BuildSerializer(_registeredObjectSerializer); - if (typeof (IJsonSerializable).IsAssignableFrom(typeToSerialize)) - return BuildSerializer(_jsonSerializableSerializer); - if (typeof (Enum).IsAssignableFrom(typeToSerialize)) + return _BuildSerializer(_registeredObjectSerializer); + if (typeof (IJsonSerializable).GetTypeInfo().IsAssignableFrom(typeInfo)) + return _BuildSerializer(_jsonSerializableSerializer); + if (typeof (Enum).GetTypeInfo().IsAssignableFrom(typeInfo)) { if (json != null) { if (json.Type == JsonValueType.Number) - return BuildSerializer(_enumValueSerializer); + return _BuildSerializer(_enumValueSerializer); if (json.Type == JsonValueType.String) - return BuildSerializer(_enumNameSerializer); + return _BuildSerializer(_enumNameSerializer); } switch (options.EnumSerializationFormat) { case EnumSerializationFormat.AsInteger: - return BuildSerializer(_enumValueSerializer); + return _BuildSerializer(_enumValueSerializer); case EnumSerializationFormat.AsName: - return BuildSerializer(_enumNameSerializer); + return _BuildSerializer(_enumNameSerializer); default: throw new ArgumentOutOfRangeException(); } } ISerializer serializer; if (_library.TryGetValue(typeToSerialize, out serializer)) - return BuildSerializer(serializer); - return BuildSerializer(_autoSerializer); + return _BuildSerializer(serializer); + return _BuildSerializer(_autoSerializer); } public static ITypeSerializer GetTypeSerializer(JsonSerializerOptions options) { return _autoSerializer; } - private static ISerializer BuildSerializer(ISerializer innerSerializer) + private static ISerializer _BuildSerializer(ISerializer innerSerializer) { return new DefaultValueSerializer(new ReferencingSerializer(innerSerializer)); } diff --git a/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs b/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs index 0e87a04..03f2555 100644 --- a/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs +++ b/Manatee.Json/Serialization/Internal/SerializerMethodPair.cs @@ -1,28 +1,27 @@ using System; using System.Reflection; -using Manatee.Json.Internal; namespace Manatee.Json.Serialization.Internal { internal class SerializerMethodPair { - public MethodInfo Serializer { get; private set; } - public MethodInfo Deserializer { get; private set; } + public MethodInfo Serializer { get; } + public MethodInfo Deserializer { get; } public SerializerMethodPair(Type type) { - Serializer = GetTypedSerializeMethod(type); - Deserializer = GetTypedDeserializeMethod(type); + Serializer = _GetTypedSerializeMethod(type); + Deserializer = _GetTypedDeserializeMethod(type); } - private static MethodInfo GetTypedSerializeMethod(Type type) + private static MethodInfo _GetTypedSerializeMethod(Type type) { - return typeof(JsonSerializer).GetMethod("Serialize") + return typeof(JsonSerializer).GetTypeInfo().GetDeclaredMethod("Serialize") .MakeGenericMethod(type); } - private static MethodInfo GetTypedDeserializeMethod(Type type) + private static MethodInfo _GetTypedDeserializeMethod(Type type) { - return typeof(JsonSerializer).GetMethod("Deserialize") + return typeof(JsonSerializer).GetTypeInfo().GetDeclaredMethod("Deserialize") .MakeGenericMethod(type); } } diff --git a/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs b/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs index 872754b..adffcbe 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/AutoSerializer.cs @@ -15,14 +15,14 @@ public JsonValue Serialize(T obj, JsonSerializer serializer) var json = new JsonObject(); var type = typeof (T); if ((serializer.Options.TypeNameSerializationBehavior != TypeNameSerializationBehavior.Never) && - (type.TypeInfo().IsAbstract || type.TypeInfo().IsInterface || (serializer.Options.TypeNameSerializationBehavior == TypeNameSerializationBehavior.Always))) + (type.GetTypeInfo().IsAbstract || type.GetTypeInfo().IsInterface || (serializer.Options.TypeNameSerializationBehavior == TypeNameSerializationBehavior.Always))) { type = obj.GetType(); json.Add(Constants.TypeKey, type.AssemblyQualifiedName); } var propertyList = ReflectionCache.GetMembers(type, serializer.Options.PropertySelectionStrategy, serializer.Options.AutoSerializeFields); - var map = SerializeValues(obj, serializer, propertyList); - ConstructJsonObject(json, map); + var map = _SerializeValues(obj, serializer, propertyList); + _ConstructJsonObject(json, map); return json.Count == 0 ? JsonValue.Null : json; } public JsonValue SerializeType(JsonSerializer serializer) @@ -30,8 +30,8 @@ public JsonValue SerializeType(JsonSerializer serializer) var json = new JsonObject(); var type = typeof (T); var propertyList = ReflectionCache.GetTypeMembers(type, serializer.Options.PropertySelectionStrategy, serializer.Options.AutoSerializeFields); - var map = SerializeTypeValues(serializer, propertyList); - ConstructJsonObject(json, map); + var map = _SerializeTypeValues(serializer, propertyList); + _ConstructJsonObject(json, map); return json.Count == 0 ? JsonValue.Null : json; } public T Deserialize(JsonValue json, JsonSerializer serializer) @@ -39,30 +39,29 @@ public T Deserialize(JsonValue json, JsonSerializer serializer) var obj = JsonSerializationAbstractionMap.CreateInstance(json, serializer.Options.Resolver); var type = obj.GetType(); var propertyList = ReflectionCache.GetMembers(type, serializer.Options.PropertySelectionStrategy, serializer.Options.AutoSerializeFields); - var map = DeserializeValues(obj, json, serializer, propertyList, !serializer.Options.CaseSensitiveDeserialization); + var map = _DeserializeValues(obj, json, serializer, propertyList, !serializer.Options.CaseSensitiveDeserialization); if ((json.Object.Count > 0) && (serializer.Options.InvalidPropertyKeyBehavior == InvalidPropertyKeyBehavior.ThrowException)) throw new TypeDoesNotContainPropertyException(type, json); - AssignObjectProperties(obj, map); + _AssignObjectProperties(obj, map); return obj; } public void DeserializeType(JsonValue json, JsonSerializer serializer) { var type = typeof (T); var propertyList = ReflectionCache.GetTypeMembers(type, serializer.Options.PropertySelectionStrategy, serializer.Options.AutoSerializeFields); - var map = DeserializeTypeValues(json, serializer, propertyList, !serializer.Options.CaseSensitiveDeserialization); + var map = _DeserializeTypeValues(json, serializer, propertyList, !serializer.Options.CaseSensitiveDeserialization); if ((json.Object.Count > 0) && (serializer.Options.InvalidPropertyKeyBehavior == InvalidPropertyKeyBehavior.ThrowException)) throw new TypeDoesNotContainPropertyException(type, json); - AssignObjectProperties(null, map); + _AssignObjectProperties(null, map); } - private static Dictionary SerializeValues(T obj, JsonSerializer serializer, IEnumerable properties) + private static Dictionary _SerializeValues(T obj, JsonSerializer serializer, IEnumerable properties) { var dict = new Dictionary(); foreach (var property in properties) { object value; Type type; - var propertyInfo = property.MemberInfo as PropertyInfo; - if (propertyInfo != null) + if (property.MemberInfo is PropertyInfo propertyInfo) { if (propertyInfo.GetIndexParameters().Any()) continue; value = propertyInfo.GetValue(obj, null); @@ -71,7 +70,7 @@ public void DeserializeType(JsonValue json, JsonSerializer serializer) } else { - var fieldInfo = (FieldInfo) property.MemberInfo; + var fieldInfo = (FieldInfo)property.MemberInfo; value = fieldInfo.GetValue(obj); if (value == null && !serializer.Options.EncodeDefaultValues) continue; type = fieldInfo.FieldType; @@ -85,22 +84,21 @@ public void DeserializeType(JsonValue json, JsonSerializer serializer) if ((json == JsonValue.Null) && !serializer.Options.EncodeDefaultValues) continue; if (serializer.Options.IncludeContentSample && json.Type == JsonValueType.Array) { - AddSample(type, json.Array, serializer); + _AddSample(type, json.Array, serializer); } dict.Add(property, json); } return dict; } - private static Dictionary SerializeTypeValues(JsonSerializer serializer, IEnumerable properties) + private static Dictionary _SerializeTypeValues(JsonSerializer serializer, IEnumerable properties) { var dict = new Dictionary(); foreach (var memberInfo in properties) { object value; Type type; - var propertyInfo = memberInfo.MemberInfo as PropertyInfo; - if (propertyInfo != null) + if (memberInfo.MemberInfo is PropertyInfo propertyInfo) { if (propertyInfo.GetIndexParameters().Any()) continue; value = propertyInfo.GetValue(null, null); @@ -109,7 +107,7 @@ public void DeserializeType(JsonValue json, JsonSerializer serializer) } else { - var fieldInfo = (FieldInfo) memberInfo.MemberInfo; + var fieldInfo = (FieldInfo)memberInfo.MemberInfo; value = fieldInfo.GetValue(null); if (value == null) continue; type = fieldInfo.FieldType; @@ -121,14 +119,14 @@ public void DeserializeType(JsonValue json, JsonSerializer serializer) } return dict; } - private static void ConstructJsonObject(JsonObject json, Dictionary memberMap) + private static void _ConstructJsonObject(JsonObject json, Dictionary memberMap) { foreach (var memberInfo in memberMap.Keys) { json.Add(memberInfo.SerializationName, memberMap[memberInfo]); } } - private static Dictionary DeserializeValues(T obj, JsonValue json, JsonSerializer serializer, IEnumerable members, bool ignoreCase) + private static Dictionary _DeserializeValues(T obj, JsonValue json, JsonSerializer serializer, IEnumerable members, bool ignoreCase) { var dict = new Dictionary(); foreach (var memberInfo in members) @@ -141,10 +139,10 @@ private static void ConstructJsonObject(JsonObject json, Dictionary DeserializeTypeValues(JsonValue json, JsonSerializer serializer, IEnumerable members, bool ignoreCase) + private static Dictionary _DeserializeTypeValues(JsonValue json, JsonSerializer serializer, IEnumerable members, bool ignoreCase) { var dict = new Dictionary(); foreach (var memberInfo in members) @@ -208,7 +206,7 @@ private static void ConstructJsonObject(JsonObject json, Dictionary memberMap) + private static void _AssignObjectProperties(object obj, Dictionary memberMap) { foreach (var entry in memberMap) { @@ -219,19 +217,19 @@ private static void AssignObjectProperties(object obj, Dictionary))) + if (collectionType.GetTypeInfo().IsGenericType && collectionType.GetGenericTypeDefinition().InheritsFrom(typeof(IEnumerable<>))) return collectionType.GetTypeArguments().First(); return typeof (object); } diff --git a/Manatee.Json/Serialization/Internal/Serializers/DefaultValueSerializer.cs b/Manatee.Json/Serialization/Internal/Serializers/DefaultValueSerializer.cs index e881bd1..0884279 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/DefaultValueSerializer.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/DefaultValueSerializer.cs @@ -18,8 +18,9 @@ public JsonValue Serialize(T obj, JsonSerializer serializer) } public T Deserialize(JsonValue json, JsonSerializer serializer) { - if (json.Type == JsonValueType.Null) return default(T); - return _innerSerializer.Deserialize(json, serializer); + return json.Type == JsonValueType.Null + ? default(T) + : _innerSerializer.Deserialize(json, serializer); } } } \ No newline at end of file diff --git a/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs b/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs index 0cdc76a..cf30bed 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/EnumNameSerializer.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; -using System.ComponentModel; +using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; -using Manatee.Json.Internal; namespace Manatee.Json.Serialization.Internal.Serializers { @@ -21,26 +20,21 @@ private class Description public JsonValue Serialize(T obj, JsonSerializer serializer) { - EnsureDescriptions(); - var attributes = typeof (T).TypeInfo().GetCustomAttributes(typeof (FlagsAttribute), false); + _EnsureDescriptions(); + var attributes = typeof (T).GetTypeInfo().GetCustomAttributes(typeof (FlagsAttribute), false); if (!attributes.Any()) { var entry = _descriptions[typeof (T)].FirstOrDefault(d => Equals(d.Value, obj)); return entry == null ? obj.ToString() : entry.String; } - return BuildFlagsValues(obj, serializer.Options.FlagsEnumSeparator); + return _BuildFlagsValues(obj, serializer.Options.FlagsEnumSeparator); } public T Deserialize(JsonValue json, JsonSerializer serializer) { - EnsureDescriptions(); + _EnsureDescriptions(); var options = serializer.Options.CaseSensitiveDeserialization -#if IOS || CORE ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; -#else - ? StringComparison.InvariantCultureIgnoreCase - : StringComparison.InvariantCulture; -#endif var entry = _descriptions[typeof (T)].FirstOrDefault(d => string.Equals(d.String, json.String, options)); if (entry == null) { @@ -49,7 +43,7 @@ public T Deserialize(JsonValue json, JsonSerializer serializer) return (T) entry.Value; } - private static void EnsureDescriptions() + private static void _EnsureDescriptions() { lock (_descriptions) { @@ -57,18 +51,18 @@ private static void EnsureDescriptions() if (_descriptions.ContainsKey(type)) return; var names = Enum.GetValues(type).Cast(); - var descriptions = names.Select(n => new Description { Value = n, String = GetDescription(n.ToString()) }).ToList(); + var descriptions = names.Select(n => new Description { Value = n, String = _GetDescription(n.ToString()) }).ToList(); _descriptions.Add(type, descriptions); } } - private static string GetDescription(string name) + private static string _GetDescription(string name) { - var type = typeof (T); - var memInfo = type.TypeInfo().GetMember(name); - var attributes = memInfo[0].GetCustomAttributes(typeof (DescriptionAttribute), false); - return attributes.Any() ? ((DescriptionAttribute)attributes.First()).Description : name; + var type = typeof(T); + var memInfo = type.GetTypeInfo().GetDeclaredField(name); + var attributes = memInfo.GetCustomAttributes(typeof(DisplayAttribute), false); + return attributes.Any() ? ((DisplayAttribute) attributes.First()).Description : name; } - private static string BuildFlagsValues(T obj, string separator) + private static string _BuildFlagsValues(T obj, string separator) { var descriptions = _descriptions[typeof (T)]; var value = Convert.ToInt64(obj); @@ -84,7 +78,7 @@ private static string BuildFlagsValues(T obj, string separator) } index--; } - return names.Join(separator); + return string.Join(separator, names); } } } \ No newline at end of file diff --git a/Manatee.Json/Serialization/Internal/Serializers/NumericSerializer.cs b/Manatee.Json/Serialization/Internal/Serializers/NumericSerializer.cs index e3f7877..2a5b97c 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/NumericSerializer.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/NumericSerializer.cs @@ -8,7 +8,7 @@ internal class NumericSerializer : ISerializer public JsonValue Serialize(T obj, JsonSerializer serializer) { - double value = Convert.ToDouble(obj); + var value = Convert.ToDouble(obj); return value; } public T Deserialize(JsonValue json, JsonSerializer serializer) diff --git a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs index 5ea2df2..838bac5 100644 --- a/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs +++ b/Manatee.Json/Serialization/Internal/Serializers/ReflectionCache.cs @@ -33,22 +33,22 @@ static ReflectionCache() public static IEnumerable GetMembers(Type type, PropertySelectionStrategy propertyTypes, bool includeFields) { - var info = InitializeInstanceCache(type); - var members = GetProperties(info, propertyTypes); + var info = _InitializeInstanceCache(type); + var members = _GetProperties(info, propertyTypes); if (includeFields) - members = members.Concat(GetFields(info)); + members = members.Concat(_GetFields(info)); return members; } public static IEnumerable GetTypeMembers(Type type, PropertySelectionStrategy propertyTypes, bool includeFields) { - var info = InitializeStaticCache(type); - var members = GetProperties(info, propertyTypes); + var info = _InitializeStaticCache(type); + var members = _GetProperties(info, propertyTypes); if (includeFields) - members = members.Concat(GetFields(info)); + members = members.Concat(_GetFields(info)); return members; } - private static IEnumerable GetProperties(ReflectionInfo info, PropertySelectionStrategy propertyTypes) + private static IEnumerable _GetProperties(ReflectionInfo info, PropertySelectionStrategy propertyTypes) { var properties = new List(); if ((propertyTypes & PropertySelectionStrategy.ReadWriteOnly) != 0) @@ -57,89 +57,81 @@ private static IEnumerable GetProperties(ReflectionInfo info, properties.AddRange(info.ReadOnlyProperties); return properties; } - private static IEnumerable GetFields(ReflectionInfo info) + private static IEnumerable _GetFields(ReflectionInfo info) { var fields = new List(); fields.AddRange(info.Fields); return fields; } - private static ReflectionInfo InitializeInstanceCache(Type type) + private static ReflectionInfo _InitializeInstanceCache(Type type) { - ReflectionInfo info; - if (!_instanceCache.TryGetValue(type, out info)) + if (!_instanceCache.TryGetValue(type, out ReflectionInfo info)) { - var read = GetInstanceProperties(type).Where(p => p.GetSetMethod() == null) - .Where(p => p.GetGetMethod() != null) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); - var readWrite = GetInstanceProperties(type).Where(p => p.GetSetMethod() != null) - .Where(p => p.GetGetMethod() != null) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); - var fields = GetInstanceFields(type).Where(p => !p.IsInitOnly) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); + var read = _GetInstanceProperties(type).Where(p => !p.SetMethod.IsPublic) + .Where(p => p.GetMethod.IsPublic) + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); + var readWrite = _GetInstanceProperties(type).Where(p => p.SetMethod.IsPublic) + .Where(p => p.GetMethod.IsPublic) + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); + var fields = _GetInstanceFields(type).Where(p => !p.IsInitOnly) + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); _instanceCache[type] = info = new ReflectionInfo(read, readWrite, fields); } return info; } - private static ReflectionInfo InitializeStaticCache(Type type) + private static ReflectionInfo _InitializeStaticCache(Type type) { - ReflectionInfo info; - if (!_staticCache.TryGetValue(type, out info)) + if (!_staticCache.TryGetValue(type, out ReflectionInfo info)) { - var read = GetStaticProperties(type).Where(p => p.GetSetMethod() == null) - .Where(p => p.GetGetMethod() != null) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); - var readWrite = GetStaticProperties(type).Where(p => p.GetSetMethod() != null) - .Where(p => p.GetGetMethod() != null) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); - var fields = GetStaticFields(type).Where(p => !p.IsInitOnly) - .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) - .Select(BuildSerializationInfo); + var read = _GetStaticProperties(type).Where(p => !p.SetMethod.IsPublic) + .Where(p => p.GetMethod.IsPublic) + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); + var readWrite = _GetStaticProperties(type).Where(p => p.SetMethod.IsPublic) + .Where(p => p.GetMethod.IsPublic) + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); + var fields = _GetStaticFields(type).Where(p => !p.IsInitOnly) + .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any()) + .Select(_BuildSerializationInfo); _staticCache[type] = info = new ReflectionInfo(read, readWrite, fields); } return info; } - private static SerializationInfo BuildSerializationInfo(MemberInfo info) + private static SerializationInfo _BuildSerializationInfo(MemberInfo info) { var mapper = (JsonMapToAttribute) info.GetCustomAttributes(typeof(JsonMapToAttribute), false).FirstOrDefault(); var name = mapper == null ? info.Name : mapper.MapToKey; return new SerializationInfo(info, name); } - private static IEnumerable GetInstanceProperties(Type type) + private static IEnumerable _GetInstanceProperties(this Type type) { -#if IOS - return type.TypeInfo().DeclaredProperties.Where(p => (!p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); -#else - return type.TypeInfo().GetProperties(BindingFlags.Instance | BindingFlags.Public); -#endif + return type.GetTypeInfo().GetAllProperties().Where(p => (!p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); } - private static IEnumerable GetStaticProperties(Type type) + private static IEnumerable _GetStaticProperties(this Type type) { -#if IOS - return type.TypeInfo().DeclaredProperties.Where(p => (p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); -#else - return type.TypeInfo().GetProperties(BindingFlags.Static | BindingFlags.Public); -#endif + return type.GetTypeInfo().GetAllProperties().Where(p => (p.GetMethod?.IsStatic ?? false) && (p.GetMethod?.IsPublic ?? false)); } - private static IEnumerable GetInstanceFields(Type type) + private static IEnumerable _GetInstanceFields(this Type type) { -#if IOS - return type.TypeInfo().DeclaredFields.Where(f => !f.IsStatic && f.IsPublic); -#else - return type.TypeInfo().GetFields(BindingFlags.Instance | BindingFlags.Public); -#endif + return type.GetTypeInfo()._GetAllFields().Where(f => !f.IsStatic && f.IsPublic); } - private static IEnumerable GetStaticFields(Type type) + private static IEnumerable _GetStaticFields(this Type type) { -#if IOS - return type.TypeInfo().DeclaredFields.Where(f => f.IsStatic && f.IsPublic); -#else - return type.TypeInfo().GetFields(BindingFlags.Static | BindingFlags.Public); -#endif + return type.GetTypeInfo()._GetAllFields().Where(f => f.IsStatic && f.IsPublic); + } + private static IEnumerable _GetAllFields(this TypeInfo type) + { + var fields = new List(); + while (type != null) + { + fields.AddRange(type.DeclaredFields); + type = type.BaseType?.GetTypeInfo(); + } + return fields; } } } \ No newline at end of file diff --git a/Manatee.Json/Serialization/Internal/TemplateGenerator.cs b/Manatee.Json/Serialization/Internal/TemplateGenerator.cs index 38705c0..8bd1703 100644 --- a/Manatee.Json/Serialization/Internal/TemplateGenerator.cs +++ b/Manatee.Json/Serialization/Internal/TemplateGenerator.cs @@ -18,11 +18,7 @@ internal static class TemplateGenerator static TemplateGenerator() { -#if IOS - _buildMethod = typeof(TemplateGenerator).GetMethod("BuildInstance"); -#else - _buildMethod = typeof(TemplateGenerator).TypeInfo().GetMethod("BuildInstance", BindingFlags.Static | BindingFlags.NonPublic); -#endif + _buildMethod = typeof(TemplateGenerator).GetTypeInfo().GetDeclaredMethod("BuildInstance"); _buildMethods = new Dictionary(); _defaultInstances = new Dictionary { @@ -38,7 +34,7 @@ public static JsonValue FromType(JsonSerializer serializer) serializer.Options.IncludeContentSample = true; _generatedTypes = new List(); - var instance = BuildInstance(serializer.Options); + var instance = _BuildInstance(serializer.Options); var json = serializer.Serialize(instance); @@ -47,7 +43,7 @@ public static JsonValue FromType(JsonSerializer serializer) return json; } - private static T BuildInstance(JsonSerializerOptions options) + private static T _BuildInstance(JsonSerializerOptions options) { var type = typeof (T); @@ -59,7 +55,7 @@ private static T BuildInstance(JsonSerializerOptions options) _generatedTypes.Add(type); T instance; - if (type.TypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { var valueType = type.GetTypeArguments().First(); var buildMethod = GetBuildMethod(valueType); @@ -69,43 +65,35 @@ private static T BuildInstance(JsonSerializerOptions options) else { instance = JsonSerializationAbstractionMap.CreateInstance(null, options.Resolver); - FillProperties(instance, options); + _FillProperties(instance, options); if (options.AutoSerializeFields) - FillFields(instance, options); + _FillFields(instance, options); } _defaultInstances[type] = instance; return instance; } - private static void FillProperties(T instance, JsonSerializerOptions options) + private static void _FillProperties(T instance, JsonSerializerOptions options) { var type = typeof (T); -#if IOS - var properties = type.TypeInfo().DeclaredProperties -#else - var properties = type.TypeInfo().GetProperties(BindingFlags.Instance | BindingFlags.Public) -#endif - .Where(p => p.GetSetMethod() != null) - .Where(p => p.GetGetMethod() != null) + var properties = type.GetTypeInfo().DeclaredProperties + .Where(p => p.SetMethod != null) + .Where(p => p.GetMethod != null) .Where(p => !p.GetCustomAttributes(typeof (JsonIgnoreAttribute), true).Any()); foreach (var propertyInfo in properties) { var propertyType = propertyInfo.PropertyType; var indexParameters = propertyInfo.GetIndexParameters().ToList(); if (indexParameters.Any()) continue; - var value = GetValue(options, propertyType); + var value = _GetValue(options, propertyType); propertyInfo.SetValue(instance, value, null); } } - private static void FillFields(T instance, JsonSerializerOptions options) + private static void _FillFields(T instance, JsonSerializerOptions options) { -#if IOS - var fields = typeof (T).TypeInfo().DeclaredFields -#else - var fields = typeof (T).TypeInfo().GetFields(BindingFlags.Instance | BindingFlags.Public) -#endif + var fields = typeof (T).GetTypeInfo().DeclaredFields .Where(p => !p.IsInitOnly) .Where(p => !p.GetCustomAttributes(typeof (JsonIgnoreAttribute), true).Any()); foreach (var fieldInfo in fields) @@ -116,7 +104,7 @@ private static void FillFields(T instance, JsonSerializerOptions options) fieldInfo.SetValue(instance, value); } } - private static object GetValue(JsonSerializerOptions options, Type propertyType) + private static object _GetValue(JsonSerializerOptions options, Type propertyType) { var buildMethod = GetBuildMethod(propertyType); var value = buildMethod.Invoke(null, new object[] {options}); @@ -124,8 +112,7 @@ private static object GetValue(JsonSerializerOptions options, Type propertyType) } internal static MethodInfo GetBuildMethod(Type type) { - MethodInfo methodInfo; - if (!_buildMethods.TryGetValue(type, out methodInfo)) + if (!_buildMethods.TryGetValue(type, out MethodInfo methodInfo)) { methodInfo = _buildMethod.MakeGenericMethod(type); _buildMethods[type] = methodInfo; diff --git a/Manatee.Json/Serialization/Internal/TypeGenerator.cs b/Manatee.Json/Serialization/Internal/TypeGenerator.cs index c2af5a9..45780ee 100644 --- a/Manatee.Json/Serialization/Internal/TypeGenerator.cs +++ b/Manatee.Json/Serialization/Internal/TypeGenerator.cs @@ -1,12 +1,10 @@ -#if !IOS && !CORE - -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; +using System.Runtime.CompilerServices; using System.Threading; -using Manatee.Json.Internal; namespace Manatee.Json.Serialization.Internal { @@ -16,66 +14,67 @@ internal static class TypeGenerator private static readonly AssemblyBuilder _assemblyBuilder; private static readonly ModuleBuilder _moduleBuilder; - private static readonly Dictionary _cache; + private static readonly Dictionary _cache; static TypeGenerator() { var assemblyName = new AssemblyName(AssemblyName); - // Note: To debug IL generation, please use the following line with your own test path. Also need to uncomment the Save() call in the Generate() method. - //_assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, @"E:\Projects\Manatee.Json\Manatee.Json.Tests\bin\Debug\"); -#if NET35 - _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); - _moduleBuilder = _assemblyBuilder.DefineDynamicModule(AssemblyName); -#else - _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndCollect); - _moduleBuilder = _assemblyBuilder.DefineDynamicModule(AssemblyName, AssemblyName + ".dll"); -#endif - _cache = new Dictionary(); + _assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndCollect); + _moduleBuilder = _assemblyBuilder.DefineDynamicModule(AssemblyName + ".dll"); + _cache = new Dictionary(); } public static T Generate() { var type = typeof (T); - Type concreteType; - if (!_cache.TryGetValue(type, out concreteType)) + if (!_cache.TryGetValue(type, out TypeInfo concreteType)) { - if (!type.IsInterface) - throw new ArgumentException($"Type generation only works for interface types. Type '{type}' is not valid."); - var typeBuilder = CreateType(type); - ImplementProperties(typeBuilder); - ImplementMethods(typeBuilder); - ImplementEvents(typeBuilder); - concreteType = typeBuilder.CreateType(); + var typeInfo = type.GetTypeInfo(); + if (!typeInfo.IsInterface) + throw new ArgumentException($"Type generation only works for interface types. Type '{type}' is not an interface."); + if (!typeInfo.IsPublic) + { + var assembly = typeInfo.Assembly; + var internalsVisible = assembly.GetCustomAttributes() + .Any(a => a.AssemblyName == AssemblyName); + if (!internalsVisible) + throw new ArgumentException($"Type generation only works for accessible interface types. Type '{type}' is not accessible. " + + $"If possible, make the type public or add '[assembly:InternalsVisibleTo(\"{AssemblyName}\")] " + + $"to assembly '{assembly.FullName}'."); + } + var typeBuilder = _CreateTypeBuilder(type); + _ImplementProperties(typeBuilder); + _ImplementMethods(typeBuilder); + _ImplementEvents(typeBuilder); + concreteType = typeBuilder.CreateTypeInfo(); _cache.Add(type, concreteType); - // Note: To debug IL generation, please uncomment the following line. Also need to use the first _assemblyBuilder assignment in the static constructor. - //_assemblyBuilder.Save(@"Manatee.Json.DynamicTypes.dll"); } - return (T) ConstructInstance(concreteType); + return (T) _ConstructInstance(concreteType.AsType()); } - private static TypeBuilder CreateType(Type type) + private static TypeBuilder _CreateTypeBuilder(Type type) { var typeBuilder = _moduleBuilder.DefineType("Concrete" + type.Name, TypeAttributes.Public); typeBuilder.AddInterfaceImplementation(type); return typeBuilder; } - private static void ImplementProperties(TypeBuilder builder) + private static void _ImplementProperties(TypeBuilder builder) { var interfaceType = typeof (T); - var properties = GetAllProperties(interfaceType); + var properties = _GetAllProperties(interfaceType); foreach (var propertyInfo in properties) { - ImplementSingleProperty(builder, propertyInfo); + _ImplementSingleProperty(builder, propertyInfo); } } - private static IEnumerable GetAllProperties(Type type) + private static IEnumerable _GetAllProperties(Type type) { - var methods = new List(type.GetProperties().Where(m => !m.IsSpecialName)); - var interfaceTypes = type.GetInterfaces(); - methods.AddRange(interfaceTypes.SelectMany(GetAllProperties)); + var methods = new List(type.GetTypeInfo().DeclaredProperties.Where(m => !m.IsSpecialName)); + var interfaceTypes = type.GetTypeInfo().ImplementedInterfaces; + methods.AddRange(interfaceTypes.SelectMany(_GetAllProperties)); return methods; } - private static void ImplementSingleProperty(TypeBuilder builder, PropertyInfo propertyInfo) + private static void _ImplementSingleProperty(TypeBuilder builder, PropertyInfo propertyInfo) { const MethodAttributes methodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual; @@ -85,17 +84,17 @@ private static void ImplementSingleProperty(TypeBuilder builder, PropertyInfo pr MethodBuilder methodBuilder; if (propertyInfo.CanRead) { - methodBuilder = builder.DefineMethod(propertyInfo.GetGetMethod().Name, methodAttr, propertyInfo.PropertyType, indexers); + methodBuilder = builder.DefineMethod(propertyInfo.GetMethod.Name, methodAttr, propertyInfo.PropertyType, indexers); var il = methodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, fieldBuilder); il.Emit(OpCodes.Ret); propertyBuilder.SetGetMethod(methodBuilder); - builder.DefineMethodOverride(methodBuilder, propertyInfo.GetGetMethod()); + builder.DefineMethodOverride(methodBuilder, propertyInfo.GetMethod); } if (propertyInfo.CanWrite) { - methodBuilder = builder.DefineMethod(propertyInfo.GetGetMethod().Name, methodAttr, null, + methodBuilder = builder.DefineMethod(propertyInfo.GetMethod.Name, methodAttr, null, indexers.Union(new[] {propertyInfo.PropertyType}).ToArray()); var il = methodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); @@ -103,26 +102,26 @@ private static void ImplementSingleProperty(TypeBuilder builder, PropertyInfo pr il.Emit(OpCodes.Stfld, fieldBuilder); il.Emit(OpCodes.Ret); propertyBuilder.SetSetMethod(methodBuilder); - builder.DefineMethodOverride(methodBuilder, propertyInfo.GetSetMethod()); + builder.DefineMethodOverride(methodBuilder, propertyInfo.SetMethod); } } - private static void ImplementMethods(TypeBuilder builder) + private static void _ImplementMethods(TypeBuilder builder) { var interfaceType = typeof(T); - var methods = GetAllMethods(interfaceType); + var methods = _GetAllMethods(interfaceType); foreach (var methodInfo in methods) { - ImplementSingleMethod(builder, methodInfo); + _ImplementSingleMethod(builder, methodInfo); } } - private static IEnumerable GetAllMethods(Type type) + private static IEnumerable _GetAllMethods(Type type) { - var methods = new List(type.GetMethods().Where(m => !m.IsSpecialName)); - var interfaceTypes = type.GetInterfaces(); - methods.AddRange(interfaceTypes.SelectMany(GetAllMethods)); + var methods = new List(type.GetTypeInfo().DeclaredMethods.Where(m => !m.IsSpecialName)); + var interfaceTypes = type.GetTypeInfo().ImplementedInterfaces; + methods.AddRange(interfaceTypes.SelectMany(_GetAllMethods)); return methods; } - private static void ImplementSingleMethod(TypeBuilder builder, MethodInfo methodInfo) + private static void _ImplementSingleMethod(TypeBuilder builder, MethodInfo methodInfo) { const MethodAttributes methodAttr = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Final; var types = methodInfo.GetParameters().Select(p => p.ParameterType).ToArray(); @@ -135,10 +134,10 @@ private static void ImplementSingleMethod(TypeBuilder builder, MethodInfo method foreach (var typeParameter in typeParameters) { var genericParameter = genericParameters.Single(p => p.Name == typeParameter.Name); - var constraints = genericParameter.GetGenericParameterConstraints(); + var constraints = genericParameter.GetTypeInfo().GetGenericParameterConstraints(); foreach (var constraint in constraints) { - if (constraint.IsInterface) typeParameter.SetInterfaceConstraints(constraint); + if (constraint.GetTypeInfo().IsInterface) typeParameter.SetInterfaceConstraints(constraint); else typeParameter.SetBaseTypeConstraint(constraint); } } @@ -152,36 +151,36 @@ private static void ImplementSingleMethod(TypeBuilder builder, MethodInfo method il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ret); } - private static void ImplementEvents(TypeBuilder builder) + private static void _ImplementEvents(TypeBuilder builder) { var interfaceType = typeof(T); - var events = GetAllEvents(interfaceType); + var events = _GetAllEvents(interfaceType); foreach (var eventInfo in events) { - ImplementSingleEvent(builder, eventInfo); + _ImplementSingleEvent(builder, eventInfo); } } - private static IEnumerable GetAllEvents(Type type) + private static IEnumerable _GetAllEvents(Type type) { - var events = new List(type.GetEvents()); - var interfaceTypes = type.GetInterfaces(); - events.AddRange(interfaceTypes.SelectMany(GetAllEvents)); + var events = new List(type.GetTypeInfo().DeclaredEvents); + var interfaceTypes = type.GetTypeInfo().ImplementedInterfaces; + events.AddRange(interfaceTypes.SelectMany(_GetAllEvents)); return events; } - private static void ImplementSingleEvent(TypeBuilder builder, EventInfo eventInfo) + private static void _ImplementSingleEvent(TypeBuilder builder, EventInfo eventInfo) { const MethodAttributes methodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.NewSlot | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Final; var fieldBuilder = builder.DefineField("_" + eventInfo.Name, eventInfo.EventHandlerType, FieldAttributes.Private); var eventBuilder = builder.DefineEvent(eventInfo.Name, EventAttributes.None, eventInfo.EventHandlerType); - var methodBuilder = builder.DefineMethod(eventInfo.GetAddMethod().Name, methodAttr, null, + var methodBuilder = builder.DefineMethod(eventInfo.AddMethod.Name, methodAttr, null, new[] {eventInfo.EventHandlerType}); - var combineMethod = typeof (Delegate).GetMethod("Combine", new[] {typeof (Delegate), typeof (Delegate)}); - var removeMethod = typeof (Delegate).GetMethod("Remove", new[] {typeof (Delegate), typeof (Delegate)}); - var compareExchangeMethod = typeof (Interlocked).GetMethods() - .Single(m => (m.Name == "CompareExchange") && m.IsGenericMethod) - .MakeGenericMethod(eventInfo.EventHandlerType); + var combineMethod = typeof (Delegate).GetRuntimeMethod("Combine", new[] {typeof (Delegate), typeof (Delegate)}); + var removeMethod = typeof (Delegate).GetRuntimeMethod("Remove", new[] {typeof (Delegate), typeof (Delegate)}); + var compareExchangeMethod = typeof(Interlocked).GetTypeInfo().DeclaredMethods + .Single(m => m.Name == "CompareExchange" && m.IsGenericMethod) + .MakeGenericMethod(eventInfo.EventHandlerType); var il = methodBuilder.GetILGenerator(); il.DeclareLocal(eventInfo.EventHandlerType); il.DeclareLocal(eventInfo.EventHandlerType); @@ -215,9 +214,9 @@ private static void ImplementSingleEvent(TypeBuilder builder, EventInfo eventInf il.Emit(OpCodes.Brtrue_S, label); il.Emit(OpCodes.Ret); eventBuilder.SetAddOnMethod(methodBuilder); - builder.DefineMethodOverride(methodBuilder, eventInfo.GetAddMethod()); + builder.DefineMethodOverride(methodBuilder, eventInfo.AddMethod); - methodBuilder = builder.DefineMethod(eventInfo.GetRemoveMethod().Name, methodAttr, null, new[] {eventInfo.EventHandlerType}); + methodBuilder = builder.DefineMethod(eventInfo.RemoveMethod.Name, methodAttr, null, new[] {eventInfo.EventHandlerType}); il = methodBuilder.GetILGenerator(); il.DeclareLocal(eventInfo.EventHandlerType); il.DeclareLocal(eventInfo.EventHandlerType); @@ -251,13 +250,11 @@ private static void ImplementSingleEvent(TypeBuilder builder, EventInfo eventInf il.Emit(OpCodes.Brtrue_S, label); il.Emit(OpCodes.Ret); eventBuilder.SetRemoveOnMethod(methodBuilder); - builder.DefineMethodOverride(methodBuilder, eventInfo.GetRemoveMethod()); + builder.DefineMethodOverride(methodBuilder, eventInfo.RemoveMethod); } - private static object ConstructInstance(Type type) + private static object _ConstructInstance(Type type) { return Activator.CreateInstance(type, null); } } } - -#endif \ No newline at end of file diff --git a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs index cee64c1..fda7945 100644 --- a/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs +++ b/Manatee.Json/Serialization/JsonSerializationAbstractionMap.cs @@ -31,11 +31,11 @@ static JsonSerializationAbstractionMap() public static void Map(MapBaseAbstractionBehavior mappingBehavior = MapBaseAbstractionBehavior.Unmapped) where TConcrete : TAbstract, new() { - if (typeof(TConcrete).TypeInfo().IsAbstract || typeof(TConcrete).TypeInfo().IsInterface) + if (typeof(TConcrete).GetTypeInfo().IsAbstract || typeof(TConcrete).GetTypeInfo().IsInterface) throw new JsonTypeMapException(); var tAbstract = typeof (TAbstract); var tConcrete = typeof (TConcrete); - MapTypes(tAbstract, tConcrete, mappingBehavior); + _MapTypes(tAbstract, tConcrete, mappingBehavior); } /// /// Applies a mapping from an open generic abstraction to an open generic concrete type. @@ -48,11 +48,11 @@ static JsonSerializationAbstractionMap() /// from . public static void MapGeneric(Type tAbstract, Type tConcrete, MapBaseAbstractionBehavior mappingBehavior = MapBaseAbstractionBehavior.Unmapped) { - if (tConcrete.TypeInfo().IsAbstract || tConcrete.TypeInfo().IsInterface) + if (tConcrete.GetTypeInfo().IsAbstract || tConcrete.GetTypeInfo().IsInterface) throw new JsonTypeMapException(tAbstract, tConcrete); if (!tConcrete.InheritsFrom(tAbstract)) throw new JsonTypeMapException(tAbstract, tConcrete); - MapTypes(tAbstract, tConcrete, mappingBehavior); + _MapTypes(tAbstract, tConcrete, mappingBehavior); } /// /// Removes a previously-assigned mapping. @@ -62,8 +62,7 @@ public static void MapGeneric(Type tAbstract, Type tConcrete, MapBaseAbstraction public static void RemoveMap(bool removeRelated = true) { var tAbstract = typeof (TAbstract); - Type tConcrete; - if (!_registry.TryGetValue(tAbstract, out tConcrete)) return; + if (!_registry.TryGetValue(tAbstract, out Type tConcrete)) return; _registry.Remove(tAbstract); if (!removeRelated) return; @@ -81,14 +80,13 @@ public static void RemoveMap(bool removeRelated = true) /// The mapped type if a mapping exists; otherwise the abstraction type. public static Type GetMap(Type type) { - if (!type.TypeInfo().IsAbstract && !type.TypeInfo().IsInterface) return type; - Type tConcrete; - if (_registry.TryGetValue(type, out tConcrete)) return tConcrete; + if (!type.GetTypeInfo().IsAbstract && !type.GetTypeInfo().IsInterface) return type; + if (_registry.TryGetValue(type, out Type tConcrete)) return tConcrete; - if (type.TypeInfo().IsGenericType) + if (type.GetTypeInfo().IsGenericType) { var genericDefinition = type.GetGenericTypeDefinition(); - var genericMatches = _registry.Where(t => t.Key.TypeInfo().IsGenericTypeDefinition && t.Key.GetGenericTypeDefinition() == genericDefinition).ToList(); + var genericMatches = _registry.Where(t => t.Key.GetTypeInfo().IsGenericTypeDefinition && t.Key.GetGenericTypeDefinition() == genericDefinition).ToList(); if (genericMatches.Any()) { var typeArguments = type.GetTypeArguments(); @@ -101,65 +99,60 @@ public static Type GetMap(Type type) internal static T CreateInstance(JsonValue json, IResolver resolver) { var type = typeof (T); - if (type.TypeInfo().IsAbstract || type.TypeInfo().IsInterface || type.TypeInfo().IsGenericType) + if (type.GetTypeInfo().IsAbstract || type.GetTypeInfo().IsInterface || type.GetTypeInfo().IsGenericType) { if ((json != null) && (json.Type == JsonValueType.Object) && (json.Object.ContainsKey(Constants.TypeKey))) { var concrete = Type.GetType(json.Object[Constants.TypeKey].String); return (T) resolver.Resolve(concrete); } - Type tConcrete; - if (!_registry.TryGetValue(type, out tConcrete)) + if (!_registry.TryGetValue(type, out Type tConcrete)) { - if (type.TypeInfo().IsGenericType) + if (type.GetTypeInfo().IsGenericType) type = type.GetGenericTypeDefinition(); _registry.TryGetValue(type, out tConcrete); } if (tConcrete != null) { - if (tConcrete.TypeInfo().IsGenericTypeDefinition) + if (tConcrete.GetTypeInfo().IsGenericTypeDefinition) tConcrete = tConcrete.MakeGenericType(typeof(T).GetTypeArguments()); return (T) resolver.Resolve(tConcrete); } -#if !IOS && !CORE - if (type.IsInterface) + if (type.GetTypeInfo().IsInterface) return TypeGenerator.Generate(); -#endif } return resolver.Resolve(); } - private static void MapTypes(Type tAbstract, Type tConcrete, MapBaseAbstractionBehavior mappingBehavior) + private static void _MapTypes(Type tAbstract, Type tConcrete, MapBaseAbstractionBehavior mappingBehavior) { _registry[tAbstract] = tConcrete; switch (mappingBehavior) { case MapBaseAbstractionBehavior.Unmapped: - MapBaseTypes(tAbstract, tConcrete, false); + _MapBaseTypes(tAbstract, tConcrete, false); break; case MapBaseAbstractionBehavior.Override: - MapBaseTypes(tAbstract, tConcrete, true); + _MapBaseTypes(tAbstract, tConcrete, true); break; } } - private static void MapBaseTypes(Type tAbstract, Type tConcrete, bool overwrite) + private static void _MapBaseTypes(Type tAbstract, Type tConcrete, bool overwrite) { if (tAbstract == null) return; - var tBase = tAbstract.TypeInfo().BaseType; - if ((tBase != null) && (overwrite || !_registry.ContainsKey(tBase))) - { + var tBase = tAbstract.GetTypeInfo().BaseType; + if (tBase != null && (overwrite || !_registry.ContainsKey(tBase))) _registry[tBase] = tConcrete; - } - MapBaseTypes(tBase, tConcrete, overwrite); - foreach (var tInterface in tAbstract.TypeInfo().GetInterfaces()) + _MapBaseTypes(tBase, tConcrete, overwrite); + foreach (var tInterface in tAbstract.GetTypeInfo().ImplementedInterfaces) { if (overwrite || !_registry.ContainsKey(tInterface)) { _registry[tInterface] = tConcrete; } - MapBaseTypes(tInterface, tConcrete, overwrite); + _MapBaseTypes(tInterface, tConcrete, overwrite); } } } diff --git a/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs b/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs index 566864a..3ae049b 100644 --- a/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs +++ b/Manatee.Json/Serialization/JsonSerializationTypeRegistry.cs @@ -39,20 +39,16 @@ public static class JsonSerializationTypeRegistry static JsonSerializationTypeRegistry() { - _delegateProviders = typeof(JsonSerializationTypeRegistry).TypeInfo().Assembly.GetTypes() - .Where(t => typeof(ISerializationDelegateProvider).IsAssignableFrom(t) && - !t.TypeInfo().IsAbstract && - t.TypeInfo().IsClass) - .Select(Activator.CreateInstance) + _delegateProviders = typeof(JsonSerializationTypeRegistry).GetTypeInfo().Assembly.DefinedTypes + .Where(t => typeof(ISerializationDelegateProvider).GetTypeInfo().IsAssignableFrom(t) && + !t.IsAbstract && + t.IsClass) + .Select(ti => Activator.CreateInstance(ti.AsType())) .Cast() .ToList(); _toJsonConverters = new Dictionary(); _fromJsonConverters = new Dictionary(); -#if IOS - _autoregistrationMethod = typeof (JsonSerializationTypeRegistry).GetMethod("RegisterProviderDelegates"); -#else - _autoregistrationMethod = typeof (JsonSerializationTypeRegistry).GetMethod("RegisterProviderDelegates", BindingFlags.Static | BindingFlags.NonPublic); -#endif + _autoregistrationMethod = typeof (JsonSerializationTypeRegistry).GetTypeInfo().GetDeclaredMethod("_RegisterProviderDelegates"); } /// @@ -95,7 +91,7 @@ public static bool IsRegistered() public static bool IsRegistered(Type type) { if (_toJsonConverters.ContainsKey(type)) return true; - if (type.TypeInfo().IsGenericTypeDefinition) return false; + if (type.GetTypeInfo().IsGenericTypeDefinition) return false; var delegateProvider = _delegateProviders.FirstOrDefault(p => p.CanHandle(type)); if (delegateProvider == null) return false; @@ -107,7 +103,7 @@ public static bool IsRegistered(Type type) internal static void Encode(this JsonSerializer serializer, T obj, out JsonValue json) { - var converter = GetToJsonConverter(); + var converter = _GetToJsonConverter(); if (converter == null) { json = null; @@ -120,7 +116,7 @@ internal static void Encode(this JsonSerializer serializer, T obj, out JsonVa } internal static void Decode(this JsonSerializer serializer, JsonValue json, out T obj) { - var converter = GetFromJsonConverter(); + var converter = _GetFromJsonConverter(); if (converter == null) { obj = default(T); @@ -132,18 +128,18 @@ internal static void Decode(this JsonSerializer serializer, JsonValue json, o } } - private static Delegate GetToJsonConverter() + private static Delegate _GetToJsonConverter() { var type = JsonSerializationAbstractionMap.GetMap(typeof(T)); return _toJsonConverters.ContainsKey(type) ? _toJsonConverters[type] : null; } - private static FromJsonDelegate GetFromJsonConverter() + private static FromJsonDelegate _GetFromJsonConverter() { var type = JsonSerializationAbstractionMap.GetMap(typeof (T)); return _fromJsonConverters.ContainsKey(type) ? (FromJsonDelegate) _fromJsonConverters[type] : null; } // ReSharper disable once UnusedMember.Local - private static void RegisterProviderDelegates(ISerializationDelegateProvider provider) + private static void _RegisterProviderDelegates(ISerializationDelegateProvider provider) { var type = typeof (T); _toJsonConverters[type] = provider.GetEncoder(); diff --git a/Manatee.Json/Serialization/JsonSerializer.cs b/Manatee.Json/Serialization/JsonSerializer.cs index 970cdaf..20b0e3c 100644 --- a/Manatee.Json/Serialization/JsonSerializer.cs +++ b/Manatee.Json/Serialization/JsonSerializer.cs @@ -20,7 +20,6 @@ public JsonSerializerOptions Options } internal SerializationPairCache SerializationMap { get; } = new SerializationPairCache(); - #region Public Methods /// /// Serializes an object to a JSON structure. /// @@ -92,6 +91,5 @@ public void DeserializeType(JsonValue json) var serializer = SerializerFactory.GetTypeSerializer(Options); serializer.DeserializeType(json, this); } - #endregion } } diff --git a/Manatee.Json/Serialization/TypeDoesNotContainPropertyException.cs b/Manatee.Json/Serialization/TypeDoesNotContainPropertyException.cs index 866b468..4ae5391 100644 --- a/Manatee.Json/Serialization/TypeDoesNotContainPropertyException.cs +++ b/Manatee.Json/Serialization/TypeDoesNotContainPropertyException.cs @@ -6,9 +6,6 @@ namespace Manatee.Json.Serialization /// Optionally thrown when deserializing and the JSON structure contains property names /// which are not valid for the type requested. /// -#if !IOS && !CORE - [Serializable] -#endif public class TypeDoesNotContainPropertyException : Exception { /// diff --git a/Manatee.Json/Serialization/TypeRegistrationException.cs b/Manatee.Json/Serialization/TypeRegistrationException.cs index e533ef3..b5468e0 100644 --- a/Manatee.Json/Serialization/TypeRegistrationException.cs +++ b/Manatee.Json/Serialization/TypeRegistrationException.cs @@ -6,15 +6,12 @@ namespace Manatee.Json.Serialization /// Thrown when /// is passed one method and a null. /// -#if !IOS && !CORE - [Serializable] -#endif public class TypeRegistrationException : Exception { /// /// Gets the type. /// - public Type Type { get; private set; } + public Type Type { get; } /// /// Initializes a new instance of the class. diff --git a/Manatee.Json/Transform/JsonTransformer.cs b/Manatee.Json/Transform/JsonTransformer.cs index e493b52..7719c25 100644 --- a/Manatee.Json/Transform/JsonTransformer.cs +++ b/Manatee.Json/Transform/JsonTransformer.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using Manatee.Json.Internal; using Manatee.Json.Path; namespace Manatee.Json.Transform @@ -18,10 +17,10 @@ public static class JsonTransformer /// The transformed JSON. public static JsonValue Transform(this JsonValue source, JsonValue template) { - return Transform(source, source, template, -1); + return _Transform(source, source, template, -1); } - private static JsonValue Transform(this JsonValue source, JsonValue localSource, JsonValue template, int index) + private static JsonValue _Transform(this JsonValue source, JsonValue localSource, JsonValue template, int index) { switch (template.Type) { @@ -30,51 +29,51 @@ private static JsonValue Transform(this JsonValue source, JsonValue localSource, case JsonValueType.Null: return template; case JsonValueType.String: - return TransformString(source, localSource, template.String, index); + return _TransformString(source, localSource, template.String, index); case JsonValueType.Object: - return TransformObject(source, localSource, template.Object, index); + return _TransformObject(source, localSource, template.Object, index); case JsonValueType.Array: - return TransformArray(source, localSource, template.Array, index); + return _TransformArray(source, localSource, template.Array, index); default: throw new ArgumentOutOfRangeException(); } } - private static JsonValue TransformObject(JsonValue source, JsonValue localSource, JsonObject template, int index) + private static JsonValue _TransformObject(JsonValue source, JsonValue localSource, JsonObject template, int index) { var obj = new JsonObject(); foreach (var property in template) { - obj[property.Key] = Transform(source, localSource, property.Value, index); + obj[property.Key] = _Transform(source, localSource, property.Value, index); } return obj; } - private static JsonValue TransformArray(JsonValue source, JsonValue localSource, JsonArray template, int index) + private static JsonValue _TransformArray(JsonValue source, JsonValue localSource, JsonArray template, int index) { if (template.Count != 2 || template[0].Type != JsonValueType.String) - return TransformArrayElements(source, localSource, template, index); - var path = TryGetPath(template[0].String); + return _TransformArrayElements(source, localSource, template, index); + var path = _TryGetPath(template[0].String); if (path == null) - return TransformArrayElements(source, localSource, template, index); + return _TransformArrayElements(source, localSource, template, index); var items = path.Evaluate(source); - return new JsonArray(items.Select((item, i) => Transform(source, item, template[1], i))); + return new JsonArray(items.Select((item, i) => _Transform(source, item, template[1], i))); } - private static JsonValue TransformArrayElements(JsonValue source, JsonValue localSource, JsonArray array, int index) + private static JsonValue _TransformArrayElements(JsonValue source, JsonValue localSource, JsonArray array, int index) { - return new JsonArray(array.Select(jv => Transform(source, localSource, jv, index))); + return new JsonArray(array.Select(jv => _Transform(source, localSource, jv, index))); } - private static JsonValue TransformString(JsonValue source, JsonValue localSource, string template, int index) + private static JsonValue _TransformString(JsonValue source, JsonValue localSource, string template, int index) { - var path = TryGetPath(template); + var path = _TryGetPath(template); if (path == null) return template; var pathIsLocal = template[0] == '@'; var items = path.Evaluate(pathIsLocal ? localSource : source); return items.Count == 1 ? items[0] : (index == -1 ? items : items[index]); } - private static JsonPath TryGetPath(string text) + private static JsonPath _TryGetPath(string text) { - if (text.IsNullOrWhiteSpace()) return null; + if (string.IsNullOrWhiteSpace(text)) return null; if (text[0] == '@') text = "$" + text.Substring(1); try diff --git a/Manatee.Json/UriExtensions.cs b/Manatee.Json/UriExtensions.cs index 7d12b52..2691d42 100644 --- a/Manatee.Json/UriExtensions.cs +++ b/Manatee.Json/UriExtensions.cs @@ -25,14 +25,6 @@ public static Uri GetParentUri(this Uri uri) var path = uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length); return new Uri(path); - - string url = uri.ToString(); - int index = url.Length - 1; - if (url[index] == '/') - index--; - while (url[index] != '/') - index--; - return new Uri(url.Substring(0, index + 1)); } } } diff --git a/Manatee.Json/XmlExtensions.cs b/Manatee.Json/XmlExtensions.cs index 84a5504..208669d 100644 --- a/Manatee.Json/XmlExtensions.cs +++ b/Manatee.Json/XmlExtensions.cs @@ -32,9 +32,9 @@ public static class XmlExtensions /// and is not a non-empty . public static XElement ToXElement(this JsonValue json, string key) { - if (key.IsNullOrWhiteSpace() && (json.Type != JsonValueType.Object)) + if (string.IsNullOrWhiteSpace(key) && json.Type != JsonValueType.Object) throw new ArgumentException(EncodingWithoutKeyError); - var name = GetXName(key); + var name = _GetXName(key); XElement xml; switch (json.Type) { @@ -42,7 +42,7 @@ public static XElement ToXElement(this JsonValue json, string key) return new XElement(name, json.Number); case JsonValueType.String: xml = new XElement(name, json.String); - if (RequiresTypeAttribute(json.String)) + if (_RequiresTypeAttribute(json.String)) xml.SetAttributeValue(TypeAttribute, "String"); return xml; case JsonValueType.Boolean: @@ -59,20 +59,20 @@ public static XElement ToXElement(this JsonValue json, string key) foreach (var kvp in json.Object) { var element = kvp.Value.ToXElement(kvp.Key); - if ((kvp.Value.Type == JsonValueType.Array) && !ContainsAttributeList(kvp.Value.Array)) + if ((kvp.Value.Type == JsonValueType.Array) && !_ContainsAttributeList(kvp.Value.Array)) xml.Add(element.Elements()); else xml.Add(element); } return xml; case JsonValueType.Array: - if (ContainsAttributeList(json.Array)) + if (_ContainsAttributeList(json.Array)) { var attributeNames = json.Array[0].Object; var attributes = new List(); foreach(var attributeName in attributeNames) { - var localName = GetXName(attributeName.Key.Substring(1)); + var localName = _GetXName(attributeName.Key.Substring(1)); var attribute = new XAttribute(localName, attributeName.Value.ToXElement(key).Value); if (attribute.IsNamespaceDeclaration) XmlNamespaceRegistry.Instance.Register(attribute.Name.LocalName,attribute.Value); @@ -129,7 +129,7 @@ public static XElement ToXElement(this JsonValue json, string key) /// The representation of the . public static JsonValue ToJson(this XElement xElement) { - return new JsonObject {{GetNamespaceForElement(xElement) + xElement.Name.LocalName, GetValue(xElement)}}; + return new JsonObject {{_GetNamespaceForElement(xElement) + xElement.Name.LocalName, _GetValue(xElement)}}; } /// /// Converts an to a . @@ -143,15 +143,15 @@ public static JsonValue ToJson(this IEnumerable xElements) foreach (var xElement in xElements) { XmlNamespaceRegistry.Instance.RegisterElement(xElement); - var name = GetNamespaceForElement(xElement) + xElement.Name.LocalName; - var newValue = GetValue(xElement); + var name = _GetNamespaceForElement(xElement) + xElement.Name.LocalName; + var newValue = _GetValue(xElement); if (json.ContainsKey(name)) { var item = json[name]; var nestAttribute = xElement.Attribute(NestAttribute); - if ((nestAttribute != null) && (nestAttribute.Value.ToLower() == "true")) + if (nestAttribute != null && nestAttribute.Value.ToLower() == "true") { - if ((newValue.Object.Count > 1) || ((newValue.Object.Count != 0) && (newValue.Object.Keys.ElementAt(0) != name))) + if (newValue.Object.Count > 1 || newValue.Object.Count != 0 && newValue.Object.Keys.ElementAt(0) != name) throw new XmlException(DecodingNestedArrayWithMismatchedKeysError); newValue = newValue.Object[name].Type == JsonValueType.Array ? newValue.Object[name] @@ -171,56 +171,54 @@ public static JsonValue ToJson(this IEnumerable xElements) return json; } - private static bool RequiresTypeAttribute(string value) + private static bool _RequiresTypeAttribute(string value) { - double d; var s = value.ToLower(); - return (s == "true") || (s == "false") || (s == "null") || double.TryParse(s, out d); + return s == "true" || s == "false" || s == "null" || double.TryParse(s, out double _); } - private static JsonValue GetValue(XElement xElement) + private static JsonValue _GetValue(XElement xElement) { var typeAttribute = xElement.Attribute(TypeAttribute); if (xElement.HasElements) - return AttachAttributes(xElement.Elements().ToJson(), xElement); - if (string.IsNullOrEmpty(xElement.Value) && (typeAttribute == null)) - return AttachAttributes(JsonValue.Null, xElement); + return _AttachAttributes(xElement.Elements().ToJson(), xElement); + if (string.IsNullOrEmpty(xElement.Value) && typeAttribute == null) + return _AttachAttributes(JsonValue.Null, xElement); var value = xElement.Value; - if ((typeAttribute != null) && (typeAttribute.Value.ToLower() == "string")) - return AttachAttributes(value, xElement); - return AttachAttributes(ParseValue(value), xElement); + if (typeAttribute != null && typeAttribute.Value.ToLower() == "string") + return _AttachAttributes(value, xElement); + return _AttachAttributes(_ParseValue(value), xElement); } - private static JsonValue AttachAttributes(JsonValue json, XElement xElement) + private static JsonValue _AttachAttributes(JsonValue json, XElement xElement) { - var attributes = xElement.Attributes().Where(a => (a.Name != NestAttribute) && (a.Name != TypeAttribute)).ToList(); + var attributes = xElement.Attributes().Where(a => (a.Name != NestAttribute) && a.Name != TypeAttribute).ToList(); if (attributes.Count == 0) return json; var obj = new JsonObject(); foreach (var xAttribute in attributes) { - var name = xAttribute.IsNamespaceDeclaration && (xAttribute.Name.LocalName != XmlNamespaceAttribute) + var name = xAttribute.IsNamespaceDeclaration && xAttribute.Name.LocalName != XmlNamespaceAttribute ? $"{XmlNamespaceAttribute}:{xAttribute.Name.LocalName}" - : GetNamespaceForElement(xElement, xAttribute.Name.NamespaceName) + xAttribute.Name.LocalName; - obj.Add($"-{name}", ParseValue(xAttribute.Value)); + : _GetNamespaceForElement(xElement, xAttribute.Name.NamespaceName) + xAttribute.Name.LocalName; + obj.Add($"-{name}", _ParseValue(xAttribute.Value)); } return new JsonArray { obj, json }; } - private static JsonValue ParseValue(string value) + private static JsonValue _ParseValue(string value) { - bool b; - if (bool.TryParse(value, out b)) + if (bool.TryParse(value, out bool b)) return b; double d; if (double.TryParse(value, out d)) return d; return value; } - private static bool ContainsAttributeList(JsonArray json) + private static bool _ContainsAttributeList(JsonArray json) { if (json.Count != 2) return false; if (json[0].Type != JsonValueType.Object) return false; return json[0].Object.Keys.All(key => key[0] == '-'); } - private static string GetNamespaceForElement(XElement xElement, string space = null) + private static string _GetNamespaceForElement(XElement xElement, string space = null) { var search = space ?? xElement.Name.NamespaceName; if (string.IsNullOrEmpty(search)) return string.Empty; @@ -238,7 +236,7 @@ private static string GetNamespaceForElement(XElement xElement, string space = n } return string.Empty; } - private static XName GetXName(string key) + private static XName _GetXName(string key) { if (key == null) return null; if (!key.Contains(":") && (key != XmlNamespaceAttribute)) return key; @@ -256,37 +254,5 @@ private static XName GetXName(string key) } return name; } - -#if !IOS && !CORE - /// - /// Converts an to an . - /// - /// An . - /// The construct of the . - /// Provided for convenience. - public static XElement ToXElement(this XmlNode node) - { - var xDoc = new XDocument(); - using (var xmlWriter = xDoc.CreateWriter()) - node.WriteTo(xmlWriter); - return xDoc.Root; - } - /// - /// Converts an to an . - /// - /// An . - /// The construct of the . - /// Provided for convenience. - public static XmlNode ToXmlNode(this XElement element) - { - using (var xmlReader = element.CreateReader()) - { - var xmlDoc = new XmlDocument(); - xmlDoc.Load(xmlReader); - return xmlDoc; - } - } - -#endif - } + } } diff --git a/Manatee.Json/nuget.ps1 b/Manatee.Json/nuget.ps1 deleted file mode 100644 index 5304dc9..0000000 --- a/Manatee.Json/nuget.ps1 +++ /dev/null @@ -1,27 +0,0 @@ -param([String]$nuspecfile) - -Write-Output "Post-build running..." - -if (!(Test-Path -path $nuspecfile)) { - Write-Output "Cannot find project/nuspec file '$nuspecfile'" - return 1 -} - -$nuget_exe = ".\.tools\nuget.exe" -$release_dir = ".\.release" - -if (!(Test-Path -path ".\.tools")){ - mkdir ".\.tools" -} - -if (!(Test-Path -path $nuget_exe)) { - Write-Output "Attempting to download nuget.exe" - $sourceNugetExe = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" - Invoke-WebRequest $sourceNugetExe -OutFile $nuget_exe -} - -Write-Output "Building project file '$nuspecfile'" - -& $nuget_exe pack "$nuspecfile" -NonInteractive -properties Configuration=Release -outputdirectory $release_dir - -exit $LASTEXITCODE \ No newline at end of file diff --git a/Manatee.Json/project.json b/Manatee.Json/project.json deleted file mode 100644 index 0d06306..0000000 --- a/Manatee.Json/project.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "dependencies": { - "NETStandard.Library": "1.6.1" - }, - "frameworks": { - "netstandard1.6": { - "buildOptions": { - "define": [ "TRACE", "CORE", "JETBRAINS_ANNOTATIONS" ] - }, - "imports": "dnxcore50" - } - }, - "buildOptions": { - "optimize": true, - "xmlDoc": true, - "keyFile": "Manatee.Json.snk" - } -} diff --git a/Manatee.Json/project.nuspec b/Manatee.Json/project.nuspec deleted file mode 100644 index 54d1b54..0000000 --- a/Manatee.Json/project.nuspec +++ /dev/null @@ -1,45 +0,0 @@ - - - - Manatee.Json - 6.0.3 - - A fully object-oriented approach to JSON manipulation, validation, and serialization that focuses on modeling the JSON structure rather than mere string parsing. - - gregsdennis - Copyright © 2016 Little Crab Solutions - https://www.github.com/gregsdennis/manatee.json - https://github.com/gregsdennis/Manatee.Json/blob/master/LICENSE.txt - https://bytebucket.org/gregsdennis/manatee.json/wiki/Resources/Manatee-Json-Logo.png - - v6.0.3 - Schema passes latest version of JSON Schema Test Suite. (#63) - - v6.0.2 - BUG FIX: Referenced schema not loaded. (#58) - - v6.0.1.1 - Repackaged - - v6.0.1 - Updated equality logic to further unify .Net-null and JSON-null. Please read Equality Comparisons section of Usage wiki page. - BUG FIX: Vague error messaging when validating schema. (#55) - - v6.0.0 - Added DocumentPath to IJsonSchema. - BUG FIX: Schema now properly resolve referenced schema relative to document path instead of application's current directory. (#50) - Removed JsonSchemaFactory.Load(string filename) in favor of JsonSchemaRegistry.Get(string uri). - - json manatee parser serializer jsonpath jsonschema transform path schema linq-to-json - - - - - - - - - - - - \ No newline at end of file diff --git a/build.bat b/build.bat index 82e1e1a..eaa65f7 100644 --- a/build.bat +++ b/build.bat @@ -8,8 +8,8 @@ if "%config%" == "" ( REM Build dotnet restore -"%programfiles(x86)%\MSBuild\14.0\Bin\MSBuild.exe" Manatee.Json.sln /p:Configuration="%config%" /m:1 /v:m /fl /flp:LogFile=msbuild.log;Verbosity=Normal /nr:false +"%programfiles(x86)%\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe" Manatee.Json.sln /p:Configuration="%config%" /m:1 /v:m /fl /flp:LogFile=msbuild.log;Verbosity=Normal /nr:false REM Package -powershell .\Manatee.Json\nuget.ps1 -nuspecfile .\Manatee.Json\project.nuspec \ No newline at end of file +"%programfiles(x86)%\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe" Manatee.Json.sln /t:pack /p:Configuration=Release \ No newline at end of file