Problem with deserialization


I am quite new in MongoDB and having some problems with reading my data using CSharp driver. I have a class with a Point class field called “APoint”. The document is created and APoint is an object with X and Y values as integers. So far so good. However when I list the documents I get this error. I am sure I need to write custom serialization and deserialization code, put I couldn’t find a decent example.

Any help is much appreciated.

System.FormatException: ‘An error occurred while deserializing the APoint field of class WindowsFormsApp1.ProgramSettings: Value class System.Drawing.Point cannot be deserialized.’

Hi @mgtheone, and welcome to the forum

This is likely because the registry doesn’t know how to deserialise System.Drawing.Point. You mentioned that the value of X and Y are integers, depending on your use case try to define the type as int. i.e.

public class MyPoint 
    public int X {get; set;}
    public int Y {get; set;}

If you still encountering this issue, could you provide:

  • MongoDB .NET/C# driver version
  • Example document
  • Example code snippet show casing the issue


Thanks Wan, I actually found a solution. I wrote a custom serializer called “MyCustomPointSerializer”. I will submit my code now.
Thanks a lot.

After some research and thinking I found a solution to this problem. A custom serializer worked fine. Note that this is used with:
public Point APoint;

public class MyCustomPointSerializer : IBsonSerializer
public Type ValueType => typeof(Point);

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Point value)
        BsonSerializer.Serialize(context.Writer, value);

    Point IBsonSerializer<Point>.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        Point p = BsonSerializer.Deserialize<Point>(context.Reader);
        return new Point(p.X, p.Y);

    public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        BsonDocument d = BsonSerializer.Deserialize<BsonDocument>(context.Reader);

        int x = 0;
        int y = 0;

        if (d["_t"] == "Point")
            x = Convert.ToInt32(d["X"]);
            y = Convert.ToInt32(d["Y"]);
        return new Point(x, y);

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
        BsonSerializer.Serialize(context.Writer, value);
1 Like