Skip to content

Serialization between .Net4.8 and .NetCore #21

@bluebat-swiss

Description

@bluebat-swiss

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);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions