Is it possible to deserialize JSON to an immutable class?
So, for example, we are using event sourcing and I should like to read in events from an EventStore stream and deserialize them into a class that represents an event and is, therefore, immutable.
I am deserializing our events using the following method:
private static object DeserializeEvent(byte[] metadata, byte[] data)
{
var eventClrTypeName = JsonObject.Parse(metadata.FromAsciiBytes()).GetUnescaped(EventClrTypeHeader);
var serializer = new JsonStringSerializer();
return serializer.DeserializeFromString(data.FromAsciiBytes(), Type.GetType(eventClrTypeName));
}
However, since I started to make the public properties on the classes read-only this method is obviously not setting the properties.
Is there a way of deserializing an object from JSON using that object’s constructor? Or do I need to construct some kind of DTO that is then passed in to the immutable event class? I’d ideally rather not.
Here’s an example of an event class that I have created:
public class BaggageAdded : IDomainEvent
{
public int NoOfBags { get; }
public BaggageAdded(int noOfBags)
{
NoOfBags = noOfBags;
}
}