问题
I have a list of objects of various data types (DateTime, int, decimal, string).
List<object> myObjects = new List<object>();
myObjects.Add(3);
myObjects.Add(3.9m);
myObjects.Add(DateTime.Now);
myObjects.Add("HELLO");
I was able to serialize this list using protobuf-net, but deserialization always throws the exception: "Additional information: Type is not expected, and no contract can be inferred: System.Object".
using (var ms = new MemoryStream())
{
Serializer.Serialize(ms, list2);
var bytes = ms.ToArray();
ms.Position = 0;
var clone = Serializer.Deserialize(typeof(List<object>), ms); //Throws exception
}
I don't have any explicit contract, I suppose that is the problem? However, I do know what are the expected types of serialized objects, but how do I tell to protobuf-net?
回答1:
Check these to see why this is a way to go:
The need for a parameterless constructor
why dynamic instead of object wouldn't have worked
why
DynamicType=true
wouldn't have workedthe need for an abstract base class and concrete implementations, by the creator of protobuf-net
why no serializer for object
Abstract base
[ProtoContract]
[ProtoInclude (1, typeof(ObjectWrapper<int>))]
[ProtoInclude(2, typeof(ObjectWrapper<decimal>))]
[ProtoInclude(3, typeof(ObjectWrapper<DateTime>))]
[ProtoInclude(4, typeof(ObjectWrapper<string>))]
abstract class ObjectWrapper {
protected ObjectWrapper() {}
abstract public object ObjectValue { get; set; }
}
Implementation
[ProtoContract()]
class ObjectWrapper<T> : ObjectWrapper
{
public ObjectWrapper(): base() { }
public ObjectWrapper(T t) { this.Value = t; }
[ProtoIgnore()]
public override object ObjectValue
{
get { return Value; }
set { Value = (T)value; }
}
[ProtoMember(1)]
public T Value { get; set; }
}
Test
var myObjects = new List<ObjectWrapper>();
myObjects.Add(new ObjectWrapper<int>(3));
myObjects.Add(new ObjectWrapper<decimal>(3.9m));
myObjects.Add(new ObjectWrapper<DateTime> (DateTime.Now));
myObjects.Add(new ObjectWrapper<string> ("HELLO"));
var clone = Serializer.DeepClone(myObjects);
来源:https://stackoverflow.com/questions/38905411/is-it-possible-to-serialize-a-list-of-system-object-objects-using-protocol-buffe