error when serializing a BsonDocument using System.Text.Json in .net 6.0

84 views Asked by At

I have a c# class as following:

public class Product
{
    public string ProductName { get; set; }
    public int ProductCount { get; set; }
    public BsonDocument ProductMetadata { get; set; }
}

The BsonDocument is coming from the MongoDB.Driver

My api code is as following:

// GET: api/<ProductController>
[HttpGet]
public Product Get()
{
    Product prod = new Product();
    prod.ProductName = "Test";
    prod.ProductCount = 20;
    var doc = new BsonDocument
    {
        { "metadata1", "val1" }
    };
    prod.ProductMetadata = doc;
    return prod;
}

When I call the Get api, I have the following error:

An unhandled exception occurred while processing the request.
InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonString' to type 'MongoDB.Bson.BsonBoolean'.
System.Text.Json.Serialization.Metadata.JsonPropertyInfo<T>.GetMemberAndWriteJson(object obj, ref WriteStack state, Utf8JsonWriter writer)
System.Text.Json.Serialization.Converters.ObjectDefaultConverter<T>.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state)
System.Text.Json.Serialization.JsonConverter<T>.TryWrite(Utf8JsonWriter writer, ref T value, JsonSerializerOptions options, ref WriteStack state)
System.Text.Json.Serialization.Metadata.JsonPropertyInfo<T>.GetMemberAndWriteJson(object obj, ref WriteStack state, Utf8JsonWriter writer)
System.Text.Json.Serialization.Converters.ObjectDefaultConverter<T>.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state)
....

It looks like the serializer is trying to cast the metadata1 to boolean! I don't know why... any idea? Thank you!

1

There are 1 answers

0
1polygon On

A custom json converter worked for me:

public class BsonJsonConverter : JsonConverter<BsonDocument>
{
    public override BsonDocument? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return BsonDocument.Parse(reader.GetString());
    }

    public override void Write(Utf8JsonWriter writer, BsonDocument value, JsonSerializerOptions options)
    {
        writer.WriteRawValue(value.ToJson());
    }
}

Usage:

public class Example
{
    [JsonConverter(typeof(BsonJsonConverter))]
    public BsonDocument Data { get; set; }
}