views:

43

answers:

1

I am having trouble figuring out how to get protobuf-net to serialize an object that derives from List< T >. I have tried adding the ProtoInclude attribute but I receive an ProtoBuf.ProtoException : Known-type List`1 for ProtoIncludeAttribute must be a direct subclass of UserTypeCollection. When I remove the ProtoInclude attrib it appears the data is not being serialized at all. I can not seem to find any examples of this situation anywhere. I am adding protobuf serialization as an option for our WS api and need to maintain compatibility with DataContractSerializer.

[CollectionDataContract(), ProtoContract(InferTagFromName = true)]
[ProtoInclude(100, typeof(List<UserType>))]
public class UserTypeCollection : List<UserType>
{ ... }

[DataContract(), ProtoContract(InferTagFromName = true)]
public class UserType { ... }
+1  A: 

ProtoInclude is used to denote sub types, not base types (after all, the base-type is already known). Also, the IList<T> handling should largely be implicit; note that the "infer..." etc do very little in the case of lists, since lists are just a sequence of the contained items.

For the following, I'm assuming that you are trying to serialize the list (as the top-most object):

I'm not on the right machine at the moment, but in the released dlls, I would expect that wrapping the list via an object would make it work:

[DataContract]
public class Foo {
    private readonly UserTypeCollection items = new UserTypeCollection();
    [DataMember(Order=1)]
    public UserTypeCollection Items {get{return items;}}
}

In "v2" I would hope that this scenario works from the outset. I'll try to test this tomorrow (when I'll have the right machine).

One other thought; subclassing List<T> isn't usually very useful, since none of the methods are virtual. Up to you, of course. And a final note - in "v2" we can describe the model externally if you want to have more control over the serialization but without impacting the types themselves.

Marc Gravell