用于序列化数据的实体已更改.如何为新实体升级序列化数据? [英] Entities used to serialize data have changed. How can the serialized data be upgraded for the new entities?

查看:82
本文介绍了用于序列化数据的实体已更改.如何为新实体升级序列化数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆简单的实体实例,我已经序列化到了一个文件.将来,我知道这些实体的结构(即,也许我会将Name重命名为Header或其他名称).问题是,我不想丢失保存在所有这些旧文件中的数据.什么是正确的方式

I have a bunch of simple entity instances that I have serialized to a file. In the future, I know that the structure of these entities (ie, maybe I will rename Name to Header or something). The thing is, I don't want to lose the data that I have saved in all these old files. What is the proper way to either

  1. 将数据从旧实体加载到新实体
  2. 升级旧文件,以便可以与新实体一起使用

注意:我认为我坚持使用二进制序列化,而不是xml序列化.

Note: I think I am stuck with binary serialization, not xml serialization.

提前谢谢!

编辑:所以我对上述情况有一个答案.我可以使用dataContractSerializer并执行类似的操作

So I have an answer for the case I have described. I can use a dataContractSerializer and do something like

[DataMember("bar")]
private string foo;

,然后在代码中更改名称,并保留用于序列化的名称.但是以下其他情况呢?

and change the name in the code and keep the same name that was used for serialization. But what about the following additional cases:

  1. 原始实体具有可以序列化的新成员
  2. 原始实体中的某些序列化成员已被删除
  3. 实际上某些成员的功能发生了变化(假设原始类具有FirstName和LastName成员,并且已重构为只有结合了两者的FullName成员)

要处理这些问题,我需要某种解释器/转换器反序列化类,但我不知道应该使用什么

To handle these, I need some sort of interpreter/translator deserialization class but I have no idea what I should use

推荐答案

我使用BinaryFormatter,然后注意这是一个 field 序列化程序,而不是属性序列化程序;您可以通过不更改字段名称来解决它.除非它是自动实现的属性,否则不能这样做.

I you have used BinaryFormatter, then note that this is a field serializer, not a property serializer; you can hack around it by not changing the field names. Unless it is an auto implemented property, in which case you can't.

说实话,如果您想灵活地更改类型,BinaryFormatter是一个糟糕的选择.基于合同的序列化器在这里更加灵活.例如,XmlSerializer和DataContractSerializer允许ou通过属性控制名称.

To be honest, BinaryFormatter is a poor choice if you want the flexibility to mutate the types. A contract-based serializer is much more flexible here. For example, XmlSerializer and DataContractSerializer allow ou to control the names via an attribute.

如果您想要二进制文件,则可以使用protobuf-net(也许是因为我写了它……)-在这里没有没有名称-只是数字标识符.但是protobuf格式是由Google 专门设计的,以实现API的轻松升级.

If you want binary, I would go with protobuf-net (perhaps because I wrote it...) - here there are no names - just numeric identifiers. But the protobuf format was designed by Google specifically to allow painless upgrade of APIs.

当然,您也可以将DTO视为永久合同;在这种情况下,请考虑使用v1 DTO,v2 DTO等.这不是我自己倾向于做的方式,但绝对是一种选择.

Of course, you might also look at a DTO as permenant contract; in which case consider having a v1 DTO, a v2 DTO etc. Not the way I tend to do it myself, but definitely an option.

这篇关于用于序列化数据的实体已更改.如何为新实体升级序列化数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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