BSON serialization of GUID's

Jul 1, 2010 at 2:14 AM

I'm trying to reduce the size of my BSON data file, and I noticed that GUID's are being encoded as 36-byte text strings ("00000000-0000-0000-0000-000000000000") rather than as 16-byte binary values.

Is there an easy way to fix this?  Or do I need to implement a custom handler somehow?

Jul 1, 2010 at 2:46 AM

Below is my initial attempt at a custom GUID converter.  Does that look right?


 

public class BsonGuidConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Guid);
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value == null)
        {
            writer.WriteNull();
        }
        else
        {
            Guid guid = (Guid)value;
            byte[] bytes = guid.ToByteArray();
            writer.WriteValue(bytes);
        }           
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        byte[] bytes = (byte[])reader.Value;
        return new Guid(bytes);
    }
}