I have two simple classes which I want to serialize with protobuf-net. Everything looks OK but when I deserialize the Body property is null. Any idea what I am doing wrong?
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using ProtoBuf;
namespace Protobuf_test
{
public class Program
{
private static void Main(string[] args)
{
var innerObject = new Inner() { Id = Guid.NewGuid() };
var outerObject = new Outer() { Body = innerObject };
using (var stream = File.Create("serialized.bin"))
{
Serializer.Serialize(stream, outerObject);
}
using (var file = File.OpenRead("serialized.bin"))
{
var deserialized = Serializer.Deserialize<Outer>(file);
}
}
}
[DataContract]
public class Inner
{
[DataMember]
public Guid Id { get; set; }
}
[DataContract]
public class Outer
{
[DataMember]
public object Body { get; set; }
}
}
Two issues:
protobuf-net requires a positive integer key per member; this can be provided via
Order=on[DataMember]. Low numbers are better, so typically this means1,2,3…the protobuf specification is a schema-bound serializer; it wants to understand the data in advance;
objectdoes not work nicely.but this would work:
There is some support for flexibly typed data (i.e.
object), but note that it is protobuf-net specific (it will not play nicely re portability). I would encourage you to look at the typed approach first. But it can do that: I’d just prefer it if you didn’t ;pIf you cannot change the existing model, then the first thing I would advise would be: add a separate DTO model that looks a lot like your existing model, but marked for serialization, and work with that – and shim between the two models. If that isn’t an option, you’ll need to configure the system, to a: define keys for members, and b: tell it to use dynamic. For example:
(note:
Serializer.*is basically a short-cut toRuntimeTypeModel.Default.*, so this configuration does talk to methods onSerializer.*)