【问题标题】:Change JSON.NET Serialization Settings更改 JSON.NET 序列化设置
【发布时间】:2015-04-20 12:36:09
【问题描述】:

我正在尝试使用 EasyNetQ 发送复杂对象,但我一直遇到此异常,因为我的对象包含引用回父对象的子对象列表:

Self referencing loop detected for property 'Parent' with type 'Domain.ParentItem'.
Path 'Entity.Children[0]'."}

我尝试过像这样更改 JSON.NET 默认设置,但这并不能解决问题:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    Formatting = Formatting.Indented,
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};

如何更改 Json 序列化程序的默认设置,以便无需创建单独的 DTO 对象即可解决此问题?

编辑:我已经尝试了可能重复的建议(正如我在原始帖子中所说的那样),但并没有解决问题。

【问题讨论】:

标签: c# json.net rabbitmq easynetq


【解决方案1】:

首先,你需要创建一个实现ISerializer interface的类。

例如:

public class MyCustomSerializaer : ISerializer
{
    // Add appropriate implementation containing your custom 
    // serialization/deserialization logic here
}

接下来,您需要创建一个方法,该方法将使用IServiceRegister 的实例注册此类的实例:

public void RegisterServices(IServiceRegister serviceRegister)
{
   serviceRegister.Register(serviceProvider => new MyCustomSerializer());
}

注意:为清楚起见,我将RegisterServices 作为单独的方法编写;但是,如果您愿意,可以使用 Action<IServiceRegister> 来代替。

最后,在调用RabbitHutch.CreateBus 时提供RegisterServices 作为参数:

var bus = RabbitHutch.CreateBus(connectionString, RegisterServices);

这将确保bus 将使用您的自定义序列化类而不是 EasyNetQ 的默认序列化程序。小心确保您的生产者和消费者使用兼容的序列化器实现;否则,您的消费者将收到他们无法反序列化的消息。

请注意,EasyNetQ 也允许替换其他组件。如需更多信息,请参阅here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多