How to change the ProtoMember index for members in a type using Protobuf.net?

I have a type like this:

[ProtoContract] class Person { [ProtoMember(1)] public string Name {get;set:} [ProtoMember(2)] public int Id {get;set;} } 

Later I realized that I needed another Age property, and added it like this:

 [ProtoContract] class Person { [ProtoMember(1)] public string Name {get;set:} [ProtoMember(3)] public int Age {get;set;} [ProtoMember(2)] public int Id {get;set;} } 

But since I'm still under development, I want to change the Age ProtoMember from 3 to 2 and update Id ProtoMember .

Is there any way to make this easy? Or do I need to temporarily create another type in order to convert it back and forth until I can serialize it to the type I want in the updated form?

+4
source share
2 answers

I assume the problem is transferring old data? If so, then v2 can do it for you; however , I would also be personally turned on to say "meh, Age is # 3, Id remains # 2" (I do not see huge advantages when changing this number).

But as an example for a more general case:

 var oldModel = RuntimeTypeModel.Create(); // "false" here means "don't apply the normal rules; I'll tell you what to do" oldModel.Add(typeof(Person), false).Add("Name", "Id"); var newModel = RuntimeTypeModel.Create(); // "true" here means it will read from the attributes etc newModel.Add(typeof(Person), true); // now: load from an old file, and write to a new: var obj = oldModel.Deserialize(inFile, null, typeof(Person)); newModel.Serialize(outFile, obj); 

Having 2 different instances of RuntimeTypeModel with different configurations, you can apply all kinds of odd transfers between data. But then again - using this just to make Age # 2 seem like a massive overkill. In fact, I would just make my class:

 [ProtoContract] class Person { [ProtoMember(1)] public string Name {get;set:} [ProtoMember(2)] public int Id {get;set;} [ProtoMember(3)] public int Age {get;set;} } 

And look! They are magical in order!

+4
source

There is nothing in the library to help you with this. Therefore, you will need to write something to update the data if you really need to.

If you have a bunch of data, you probably just leave the field id as it is. It does not really matter. ID 1-16 I think that use only 1 byte as a field tag, higher numbers use more bytes.

The advantage of leaving the identifier as such is that it gives you forward and backward compatibility.

+1
source

All Articles