Nock
Nock

Reputation: 6609

Serializing unknown types

Ok, I'll try to explain more clearly what I tried here

I understand that protobuf is a protocol that works with known types, you serialize an object of a given type which contains data that you also know.

I would really like to know if there's a way with Marc's implementation to serialize [ProtoMember] of type object, which could point to an instance of a basic type or a collection that's already managed by the library.

Looks like it's not, but I'm a bit frustrated because I feel Marc's library could do it, considering all the reflection/gen stuffs it's already doing.

It wouldn't be fully compliant with the protocol, but I don't care as I'm using the same libraries on both ends in a close circuit fashion.

I really need to serialize, for instance, a Dictionary<int, string> from a ProtoMember of type Object.

Upvotes: 2

Views: 522

Answers (2)

bsguedes
bsguedes

Reputation: 791

What about the serialization of primitive types from ProtoMembers defined as objects? I recall an issue dating from 2011 on this subject (https://code.google.com/p/protobuf-net/issues/detail?id=175), do we have any update on this?

What I'm trying to do is to maintain compatibility with files that were serialized using the BinaryFormatter class from .NET.

(sorry for writing this here, I don't have enough rep to add a comment or something like that)

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062780

For single objects, there is a hack in place - DynamicType=true on the [ProtoMember]. It isn't pretty, and it isn't clever, and it isn't what I would call "reliable". I would strongly suggest finding just about any alternative approach. It also does not work with lists. The inheritance support is much better, and one neat trick is generic inheritance, i.e.

[ProtoContract]
[ProtoInclude(1, typeof(Foo<int>))]
[ProtoInclude(2, typeof(Foo<string>))]
[ProtoInclude(3, typeof(Foo<Customer>))]
// etc for expected types
public abstract class Foo {
    public abstract object Value { get; }
}
[ProtoContract]
public sealed class Foo<T> : Foo {
    public override object Value { get { return TypedValue; } }
    [ProtoMember(1)]
    public T TypedValue {get;set;}
}

and serialize a Foo instead of an object.

Upvotes: 2

Related Questions