简体   繁体   English

从 BinaryFormatter 序列化切换而不改变太多:大数据和循环引用

[英]Switch from BinaryFormatter serialization without changing much: big data and circular references

In our application which is maintained for years we use BinaryFormatter serialization of big data objects containing loads of collections and circular references.在我们维护多年的应用程序中,我们使用包含大量集合和循环引用的大数据对象的 BinaryFormatter 序列化。 Serialization takes almost forever (~20 seconds) and takes much of CPU usage.序列化几乎需要永远(~20 秒)并占用大量 CPU。 I'd like to switch from this type of serialization to something better and light but without changing the code much as there was not much time given.我想从这种类型的序列化切换到更好、更轻的序列化,但由于没有太多时间而没有太多更改代码。

I've tried many of the solutions but some of them need:我已经尝试了许多解决方案,但其中一些需要:

  • class decorating or too many code changes (eg ProtoBuf );类装饰或代码更改过多(例如ProtoBuf );
  • doesn't allow circular references (eg MsgPack );不允许循环引用(例如MsgPack );

Is there a way to smoothly switch to another and better serializer without pain and improve serialization process?有没有一种方法可以轻松切换到另一个更好的序列化程序并改进序列化过程?

After doing some research and spending a day on implementing available solutions - I'll go with Json.NET .在做了一些研究并花一天时间实施可用的解决方案之后 - 我将使用Json.NET

I didn't have to change much to switch from BinaryFormatter, even the serializer attributes for objects haven't change.从 BinaryFormatter 切换时,我不需要做太多更改,甚至对象的序列化程序属性也没有更改。 It runs way faster (~2 seconds with the same object size) and everything seems to work properly.它运行得更快(大约 2 秒,对象大小相同)并且一切似乎都正常工作。

To pass the circular references and other errors I had to configure serializer:为了传递循环引用和其他错误,我必须配置序列化程序:

JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
serializer.NullValueHandling = NullValueHandling.Ignore;
serializer.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
serializer.PreserveReferencesHandling = PreserveReferencesHandling.Objects;

using (StreamWriter sw = new StreamWriter(fileName))
{
    using (JsonWriter writer = new JsonTextWriter(sw))
    {
        serializer.Serialize(writer, dbObject);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM