Removing a deserialization of a single structure field using Protobuf.net

I have a question regarding deserialization using Protobuf.Net. I am trying to replace XMLSerializer with it, and I cannot find a way to deserialize a single field from a file.
I need information if the file has been modified, which is one of the fields in the saved structure.

Is it possible? If so, can I ask for help?

Hello

+4
source share
1 answer

In most cases, frankly, you can just deserialize all of this - it will be fast, etc. However, if you really want to limit it, there are several options.

The simplest is simply to create a smaller model, only with the information you want on it. So: if your original model has 46 fields, 5 of which are collections, etc., but you just want the Version , which is in field 12, and then:

 [ProtoContract] public class InsertNameHere { [ProtoMember(12)] public int Version {get;set;} } 

Now deserialize that:

 var obj = Serializer.Deserialize<InsertNameHere>(source); int version = obj.Version; 

This will work because protobuf-net is contract based; it doesn't have to be exactly the same type if it looks close enough. However, a more advanced approach would be to use ProtoReader :

 int version = 0; using (var reader = new ProtoReader(source, RuntimeTypeModel.Default, null)) { int field; bool keepReading = true; while ((field = reader.ReadFieldHeader()) > 0 && keepReading) { switch (field) { case 12: version = reader.ReadInt32(); // STOP LOOPING (leaves the stream partly-read) keepReading = false; break; default: reader.SkipField(); break; } } } 

The reason you might want to use the above is because it may stop looking earlier - that is, as soon as we find our field 12, we can kill the reader without processing the rest of the file. As a rule, I would use only the second approach, if we know that the data is large, and we do not want this.

In technical terms, protobuf has a small header, so in theory there may be another "field 12" at the end of the file. By definition, this β€œlast value wins,” so a short circuit in the above may (theoretically) give you a different answer. BUT! This is very unlikely, and you usually know if you use the attached messages. It just DOES NOT APPLY to most people.

+4
source

Source: https://habr.com/ru/post/1435922/


All Articles