gregsdennis/Manatee.Json

How to make a custom serializer for an external type?

svenskmand opened this issue · 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 :)

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());