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

Serialization between .Net4.8 and .NetCore #21

Open bluebat-swiss opened 2 years ago

bluebat-swiss commented 2 years ago

Hi First of all, thank you sharing your fantastic code with the community. it saved me HOURS of developing an own solution!

I had some problems serializing between a .Net4.8 and .NetCore assembly. Because Microsoft changed the assembly of some basic .Net types like String, Guid, ...

I solved the problem by a little change on the TypeNameConverter. When setting the new Property UseSimpleNameForKnownDotNetTypes, the ConvertToTypeName() only uses the FullName of basic .Net types. The Type.GetType() on the other hand is able to resolve it (see code below).

Or do you have a better solution to this scenario? Cheers, jaz (bluebat)

public sealed class TypeNameConverter : ITypeNameConverter
{
    // .NetCore changed the FQN of some basic types like String so .Net4.8 can not GetType() of System.String with FQN of .NetCore, but can handle when used with simple names.
    public bool UseSimpleNameForKnownDotNetTypes { get; private set; }

    ... some code inbetween ...

    public string ConvertToTypeName(Type type)
    {
        ... some code inbetween ...

        if (UseSimpleNameForKnownDotNetTypes && IsKnownDotNetBaseType(type))
            typename = type.FullName;

        ... some code inbetween ...
    }

    public static bool IsKnownDotNetBaseType(Type type)
    {
        // enums must be serialized into numbers
        if (type.IsEnum)
            return false;

        // Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, Single
        if (type.IsPrimitive)
            return true;

        // DBNull, Decimal, DateTime, String
        TypeCode typeCode = Type.GetTypeCode(type);
        bool hasKnownTypeCode = typeCode != TypeCode.Object && typeCode != TypeCode.Empty;
        if (hasKnownTypeCode)
            return true;

        return type == typeof(Guid) ||
               type == typeof(Version);
    }
}
bentorkington commented 3 months ago

Thank you so much for documenting this! This would be a very useful addition to the README.md.