2

Is it possible to (de)serialize a list of heterogeneous objects?

Lars Truijens
  • 42,837
  • 6
  • 126
  • 143
mark
  • 59,016
  • 79
  • 296
  • 580

1 Answers1

2

A List<object> poses a number of challenges for a serialization format that does not include type metadata... but as always, there are tricks, traps, and workarounds.

If you mean at the outermost level, there are a few options here that revolve around using a different tag(/field-number) to indicate the message type. This is useful on an API (for example, a socket conversation) where different messages might be expected at any time. As example would be: How can I send multiple types of objects across Protobuf?

Inside a message is somewhat trickier; if the list of candidate types is small, then a reasonable workaround is something like presented here: Protobuf attributes with a hierarchy of generic classes, i.e. treating each anticipated type as a specialization.

If the type can't be predicted, then v2 includes another workaround, but including more metadata than normal; see http://marcgravell.blogspot.com/2011/03/objects-graphs-and-all-that-jazz.html

Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • OK, I get the picture. My first question (more are likely to follow) is it possible to gain the ProtoInclude effect without actually touching the base type declaration. Using a model, probably? In case of List I would like to use ProtoInclude on the object type, but obviously I cannot touch its declaration. – mark May 22 '11 at 12:01
  • If it truly is a `List` and cant change, then attributes-or-not; currently the last method described is the only viable option. I would recommend, however, using a DTO stack more amenable to the serialization. Re the includes: yes, they can be added via a RuntimeTypeModel – Marc Gravell May 22 '11 at 12:07