polenter / SharpSerializer

SharpSerializer can serialize types like: multidimensional array, nested array, array-of-arrays, polymorphic object (where value is inherited from the property type), generic type, generic listing (i.e. dictionary, collection) and many more, with a single line of code
https://www.sharpserializer.net
Other
114 stars 28 forks source link

Cannot serialize an array when using .NET Core, .NET 5 or later #19

Open EliAaron opened 2 years ago

EliAaron commented 2 years ago

Note: This issue seems to already be reported in previous issues but the exact case and cause where not provided.

Bug description

When using SharpSerializer NuGet package in a project targeting platforms .NET Core, .NET 5 or later, serializing an array will throw an error:

System.NullReferenceException: 'Object reference not set to an instance of an object.' When using the NuGet package in a .Net Framework project this did not happen.

Bug source

Before I go in to details, it is needed to mention that the SharpSerializer project targets the following platforms: ".NET Standard 1.0", ".NET Standard 1.3", ".NET Framework 4.5.2", so a .NET Core or .NET 5 project will use the .NET Standard version.

I downloaded the source code and ran the same code and got the same error. The error occurred in class ArrayAnalyzer ("master/SharpSerializer/Core/ArrayAnalyzer.cs"). Method getLength calls arrayType.GetMethod("GetLength"); to get the MthodInfo of the array Type needed for serialization. In .Net Framework and .Net Standard 2.0+ this simply calls the Type.GetMethod method. In .NET Standard lower than 2.0, this method does not exist. To overcome this, an extension method for Type was added in class TypeExtensions.cs ("master/SharpSerializer/Core/TypeExtensions.cs"). The extension method calls type.GetTypeInfo().GetDeclaredMethod(…) to get the MthodInfo. The problem is that declared methods are only methods declared by the current type, not by inherited types, so the MthodInfo returned is null.

Solution

The SharpSerializer project target platforms needs to be updated. Option 1: update the project to target ".NET Standard 2.0" or higher and the extension method will not be required. Option 2: update the project to target ".NET Standard 1.5" or higher and change the extension to call type.GetTypeInfo().GetMethod(…).