Question

We used JSON.NET to serialize our data together with OnDeserialized attribute to execute custom code after deserialization:

[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
    ...
}

Now we try to use protobuf instead of JSON.NET and this method is not executing. Is there another way to achieve this behaviour with protobuf.net?

Here is an example that doesn't work:

class Program
{
    static void Main(string[] args)
    {
        RuntimeTypeModel.Default.Add(typeof (Profile), false).Add(1000, "Id").Add(1001, "Text");

        var test = new Profile {Id = Guid.NewGuid(), Text = "123"};

        using (var memoryStream = new MemoryStream())
        {
            Serializer.Serialize(memoryStream, test);

            memoryStream.Seek(0, SeekOrigin.Begin);

            var deserialized =  Serializer.Deserialize<Profile>(memoryStream);

            Console.WriteLine(deserialized.Text); // should output "changed"
            Console.ReadLine();
        }
    }
}

[ProtoContract]
public class Profile
{
    public Guid Id { get; set; }
    public string Text { get; set; }

    [OnDeserialized]
    internal void OnDeserializedMethod(StreamingContext context)
    {
        Text = "changed";
    }
}
Était-ce utile?

La solution

Works fine for me:

[ProtoContract]
public class Foo
{
    [OnDeserialized]
    internal void OnDeserializedMethod(StreamingContext context)
    {
        Console.WriteLine("OnDeserializedMethod");
    }

    [ProtoMember(1)]
    public string Bar { get;set; }

    static void Main()
    {
        var foo = new Foo { Bar = "abc" };
        var clone = Serializer.DeepClone(foo);
        Console.WriteLine(clone.Bar);
    }
}

Output:

OnDeserializedMethod
abc

Can you be more specific? Perhaps showing a complete example that reproduces what you are seeing? Also: are you sure you are using protobuf-net? Some people get very confused between protobuf-net and protobuf-csharp-port. I cannot comment on what features the latter supports.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top