I’m trying to write serialization code for a class that looks like this:
public class EventMessage
{
public Dictionary<string, object> Headers { get; set; }
public object Body { get; set; }
}
The ‘object’ type members in this class hold objects from a quite small (basically, restricted to one assembly + basic CLR types) type set. So I figured i could simply list those classes as subtypes of object class like this:
model.Add(typeof(object), false)
.AddSubType(1, typeof(X))
.AddSubType(2, typeof(Y))
....
This way I don’t have to embed type information into the serialized message since the deserialization of the object class itself works much like a switch statement – it checks which one of the tags is present in the message and deserializes to appropriate type. I like this, because then I can freely rename classes and move them around assemblies without breaking things.
This worked great in my tests until I started testing headers, which mostly contain string data. I cannot mark string as a subtype of object since I’m getting this exception:
Data of this type has inbuilt behaviour, and cannot be added to a model in this way: System.String
Is there any way I can achieve this behavior or do I have to embed type information inside messages to serialize such class?
protobuf-net stores structured data;
objectis inherently not structured, and it won’t let you simply declare subclasses forobject, nor will it let you monkey with fundamental types such asstring, which has very particular rules for serialization.If it did, that’s a bug; there’s no way that should work. At all. It certainly isn’t a supported scenario, and won’t be guaranteed to do the right thing (it could also significantly break things). I will be changing the code to explicitly cause an exception in this case. I’m adding the following, to be fixed ASAP:Hmmm…. I though this was an invalid scenario, but my regression tests highlight that there is some “prior art” for this, specifically: Why string interning on serialization in protobuf-net does not work in this example?
(which is why every time I answer a non-trivial protobuf-net question, I add it as a regression test, so I wasn’t lying)
I guess I shouldn’t exclude it, but please think of the kittens: that is not my recommended way of doing it. I guess I can’t kill it now, though. Emphasis, though: I cannot enable this for adding
string(etc) as a sub-type. Consider that API message-type only, meaning your customclass/structs.protobuf-net doesn’t usually embed type information either ;p Although there is some “dynamic” support that does include type information, but it isn’t needed for this scenario.
The supported way to do this without embedding any type information would be to encapsulate the values you want, something like: