handling name space changes during deserialization of JSON String

后端 未结 1 1551
栀梦
栀梦 2021-01-24 17:55

I have 2 applications that are communicate amongst each other with the help of a redis Server, In my first application i am able to serialize and de serialize and object of the

1条回答
  •  深忆病人
    2021-01-24 18:20

    The format of the "$type" is officially hardcoded to include the CLR namespace of the sending system. So, you can either:

    1. Rename your CLR namespaces to match those of the sending system, or

    2. Subclass the DefaultSerializationBinder and use it to rename the CLR namespace names during deserialization by setting it in the JsonSerializerSettings.Binder.

    The following is a first cut at doing this:

    public class NamespaceMappingSerializationBinder : DefaultSerializationBinder
    {
        public string FromNamespace { get; set; }
    
        public string ToNamespace { get; set; }
    
        public override Type BindToType(string assemblyName, string typeName)
        {
            string fixedTypeName;
            if (FromNamespace != null && ToNamespace != null)
            {
                fixedTypeName = typeName.Replace(FromNamespace, ToNamespace);
            }
            else
            {
                fixedTypeName = typeName;
            }
            var type = base.BindToType(assemblyName, fixedTypeName);
            return type;
        }
    }
    

    Then, when you deserialize your JSON, set the Binder in the JsonSerializerSettings like so:

    JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, Binder = new NamespaceMappingSerializationBinder { FromNamespace = "From Namespace", ToNamespace = "Your Namespace" } };
    

    The type name parsing in the above is extremely crude. I found a much smarter parser here: How to parse C# generic type names?. You might also need to extend the custom Binder to have a dictionary of mappings.

    Similarly, if you need to remap the namespace names on serialization, and are working in .Net 4.0 or above, you can override BindToName.

    0 讨论(0)
提交回复
热议问题