kobi7
kobi7

Reputation: 971

how to use Protobuf-net for complex objects?

we're using wpf, and would like to serialize a complex object -- a view model.

Using binary formatter, I can just add an attribute [Serializable], and it would automatically work for the entire class, recursively.

Do we have something similar in protobuf?

Also, where is the documentation?

I learned about protoinclude, and protomembers, but these are complex objects that may change.

We want to use protobuf because it is compact, fast, and portable. But I don't rule out other options, if it accomplishes the same goals, more or less, and is easy to use. Please answer or suggest options. Thank you

Upvotes: 2

Views: 2208

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063864

BinaryFormatter manages this by including the field name in the output, which is both verbose and brittle (for example, it won't withstand changing something from a field+property to an automatically implemented property).

If you want to do something similar in protobuf-net, you can use "ImplicitFields", however, note that this assigns an integer key to each member alphabetically, so is only suitable if your model is totally fixed as a contract and will not add/rename members as this will break the contract (meaning: you can't deserialize existing data correctly). For example:

[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]
public class Foo {...} // all public fields and properties are serialized,
                       // similar to XmlSerializer

[ProtoContract(ImplicitFields = ImplicitFields.AllFields)]
public class Bar {...} // all fields (not properties; public or private)
                       // are serialized, similar to BinaryFormatter

If your contract is not totally fixed, it would be preferable to explicitly assign a key to each serialized member, which can be done in a great many ways. The simplest being:

[ProtoContract]
public class Foo {
    [ProtoMember(1)]
    public int A {get;set;}

    ...
} 

Upvotes: 3

Related Questions