Hi Guys,
I am new to MongoDB and have been going through the C# driver doc and am a little lost as to how to implement custom serializers. Could anyone help me on this please?
It all started when I tried to store an object that contained System.Drawing.Color as one of its properties and it turns out, because Color is a struct and structs are value type and therefore it has to be custom handled for MongoDB.
I modified the code linked above as follows but now at fieldInfo.SetValue(result, value); it says no set method found. i understand what is happening but not sure WHY it is though.
could any one help or at least suggest an alternative solution>
thanks in advance!
public override T Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var reader = context.Reader;
var nt = args.NominalType;
var result = (object)(new T()); //Activator.CreateInstance(nt));
reader.ReadStartDocument();
while (reader.State != BsonReaderState.EndOfDocument)
{
var state = context.Reader.State;
Debug.WriteLine($"State: {state}");
switch (state)
{
case BsonReaderState.Name:
var name = reader.ReadName(new Utf8NameDecoder());
Debug.WriteLine(name);
var fieldInfo = nt.GetField(name);
object value = null;
if (fieldInfo != null)
{
value = BsonSerializer.Deserialize(reader, fieldInfo.FieldType);
fieldInfo.SetValue(result, value);
Debug.WriteLine($"Name: {name}, Value: {value}");
}
else
{
var propertyInfo = nt.GetProperty(name);
if (propertyInfo != null)
{
value = BsonSerializer.Deserialize(reader, propertyInfo.PropertyType);
if (!propertyInfo.CanWrite) break;
propertyInfo.SetValue(result, value, null);
Debug.WriteLine($"Name: {name}, Value: {value}");
}
}
break;
case BsonReaderState.Type:
var type = reader.ReadBsonType();
Debug.WriteLine(type);
break;
case BsonReaderState.Value:
reader.SkipValue();
break;
}
}
reader.ReadEndDocument();
Debug.WriteLine("============================");
return (T) result;
}