3

The JSON data I get from my API includes the types of the objects. I want to deserialize these types using a custom serialization binder. The namespaces stays, the assembly changes.

public class SerializationBinder : Newtonsoft.Json.SerializationBinder
{
    // Type / Assembly Dictionary
    private Dictionary<String, String> KnownCoreTypes = new Dictionary<string, string>
    {
        {"My.Custom.NameSpace.Type", "Core" }
    };

    public override Type BindToType(string assemblyName, string typeName)
    {
        Type tmpTypeToDeserialize = null;
        string tmpActualValue;
        if (KnownCoreTypes.TryGetValue(typeName, out tmpActualValue) && tmpActualValue == assemblyName)
        {
              assemblyName = typeof(SerializationBinder).GetTypeInfo().Assembly.FullName;
        }

        // The following line of code returns the type.
        tmpTypeToDeserialize = Type.GetType($"{typeName}, {assemblyName}");

        return tmpTypeToDeserialize;
    }
}

But what if I have a collection of My.Custom.NameSpace.Type?

How do I resolve System.Collections.Generic.List'1[[My.Custom.NameSpace.Type, Core]], mscorlib?

R.J. Dunnill
  • 2,049
  • 3
  • 10
  • 21
greenhoorn
  • 1,601
  • 2
  • 15
  • 39
  • You have to parse the [generic `typeName` string](http://stackoverflow.com/q/10479301/3744182) into generic components, recursively bind to each, then combine them with `MakeGenericType`. See for instance [this answer](http://stackoverflow.com/a/19927484/3744182) which uses a `Regex`. – dbc Jan 20 '17 at 19:38

0 Answers0