Manatee.Json icon indicating copy to clipboard operation
Manatee.Json copied to clipboard

How to make a custom serializer for an external type?

Open svenskmand opened this issue 3 years ago • 1 comments

Hi :),

while reading the documentation, I found some talk about "custom serializers", but there was no explanation of what they where or how to use them.

My concrete problem is that I want to use DateTimeOffset as the default timestamp type in my code, but it does not get serialized, only DateTime does, but I want the timezone information. Then I looked in the documentation and found this mentioning "custom serializers", but no information about what they are or how to use them. Any help here would be very appreciated :)

svenskmand avatar Feb 11 '21 09:02 svenskmand

I figured it out, there was a hidden link to some other version of the same documentation where I managed to find this page, that explained how to use the ISerializer interface to accomplish what I wanted :)

I ended up with this implementation, in case anybody else would like to do the same:

private class DateTimeOffsetSerializer : ISerializer {
	public bool ShouldMaintainReferences => false;

	public object Deserialize(DeserializationContext context) {
		return DateTimeOffset.Parse(context.LocalValue.String);
	}

	public bool Handles(SerializationContextBase context) {
		return context.InferredType == typeof(DateTimeOffset)
			|| context.RequestedType == typeof(DateTimeOffset);
	}

	public JsonValue Serialize(SerializationContext context) {
		var timestamp = (DateTimeOffset) context.Source;
		return new JsonValue(timestamp.UtcDateTime.ToString("O"));
	}
}

and then I registered this once globally like this with this call:

SerializerFactory.AddSerializer(new DateTimeOffsetSerializer());

svenskmand avatar Feb 11 '21 10:02 svenskmand