Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialization between .Net4.8 and .NetCore #21

Open
bluebat-swiss opened this issue Jan 25, 2022 · 1 comment
Open

Serialization between .Net4.8 and .NetCore #21

bluebat-swiss opened this issue Jan 25, 2022 · 1 comment

Comments

@bluebat-swiss
Copy link

bluebat-swiss commented Jan 25, 2022

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants