使用TypeNameHandling.All处理名称空间更改 [英] Handling namespace changes with TypeNameHandling.All

查看:52
本文介绍了使用TypeNameHandling.All处理名称空间更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法通过JSON.net TypeNameHandling解决了自己的问题.我正在使用RavenDB存储JSON格式的对象,并将JSON.net序列化器的TypeNameHandling设置为true,以便处理我已有的继承结构.

I managed to get my self into a fix with the JSON.net TypeNameHandling. I am storing a JSON formatted object using RavenDB and set the TypeNameHandling of the JSON.net serializer to true in order to deal with an inheritance structure I have in place.

我需要更改要存储的文档的名称空间,因此现在将其反序列化时会引发错误"JSON中指定的错误解析类型",因为对JSON文档中类型的引用不再存在.

I needed to change the namespace of the document which I am storing, so now when it is deserialzed it is throws the error "Error resolving type specified in JSON" because the reference to the type in the JSON document no longer exists.

是否可以拦截Json反序列化以便进行某种滚动迁移?

Is it possible to intercept the Json deserialization in order to do some kind of rolling migration?

谢谢

推荐答案

好,知道了.最后,它非常简单.您需要重写DefaultSerializationBinder,该负责从文档创建.Net类型.由于我的json文档中包含旧的名称空间,因此我需要拦截该类型的创建以返回正确的类型.我整理了一个简单的实现,可以在创建JSON序列化程序时配置迁移".

Ok, figured it out. In the end it was pretty straight forward. You need to override the DefaultSerializationBinder which is responsible for creating the .Net type from the document. Since my json document has the old namespace in it, I needed to intercept the creation of that type to return the correct type. I put together a simple implementation which will allow you to configure "migrations" when the JSON serializer is created.

    public class NamespaceMigrationSerializationBinder : DefaultSerializationBinder
    {
        private readonly INamespaceMigration[] _migrations;

        public NamespaceMigrationSerializationBinder(params INamespaceMigration[] migrations)
        {
            _migrations = migrations;
        }

        public override Type BindToType(string assemblyName, string typeName)
        {
            var migration = _migrations.SingleOrDefault(p => p.FromAssembly == assemblyName && p.FromType == typeName);
            if(migration != null)
            {
                return migration.ToType;
            }
            return base.BindToType(assemblyName, typeName);
        }
    }

界面在哪里

public interface INamespaceMigration
{
    string FromAssembly { get; }

    string FromType { get; }

    Type ToType { get; }
}

这篇关于使用TypeNameHandling.All处理名称空间更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆