在.net 6.0中使用System.Text.Json序列化BsonDocument时出错

问题描述 投票:0回答:1

我有一个 C# 类,如下:

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

BsonDocument 来自 MongoDB.Driver

我的api代码如下:

// 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;
}

当我调用Get api时,出现以下错误:

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)
....

看起来序列化器正在尝试将metadata1转换为布尔值!我不知道为什么... 任何想法? 谢谢!

.net-6.0 mongodb-.net-driver json-serialization bsondocument
1个回答
0
投票

自定义 json 转换器对我有用:

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());
    }
}

用途:

public class Example
{
    [JsonConverter(typeof(BsonJsonConverter))]
    public BsonDocument Data { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.