I’m trying to serialize some objects with protobuf-net, but unfortunately they make liberal use of DateTimeOffset, which is not yet supported by protobuf-net. This leads to lots of:
No serializer defined for type: System.DateTimeOffset
Can I define my own serialization routine for unknown types? (The same question was asked earlier, but his problem was worked around.)
I’m using the latest protobuf-net beta, v2.0.0.431, under .NET 4 if it matters. I’m also using runtime definitions, so I have no way to declaratively specify how certain properties are to be handled.
There are two ways of approaching the issue of unknown “common” types; the first is to use a shim property, for example a property that represents the value as something similar (a
stringorlongfor example):The other approach is a surrogate, which is a second protobuf contract that is automatically substituted. The requirements to use a surrogate are:
DateTimeOffsetandDateTimeOffsetSurrogate)SetSurrogate(surrogateType)to educate protobuf-net, for exampleRuntimeTypeModel.Default.Add(typeof(DateTimeOffset), false).SetSurrogate(typeof(DateTimeOffsetSurrogate));the shim property is simpler, but requires repeat per-member. The surrogate is applied automatically to all instances of the type within the model. The surrogate then follows standard protobuf-net rules, so you would indicate which members to serialize, etc.
EDIT: Adding code example
Then register it like this