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!
A custom json converter worked for me:
Usage: