在控制器中将弱类型Bson文档序列化为JSON



我对MongoDB驱动程序有问题。我正在编写一个由JavaScript前端使用的.Net Core Web api。有一个ParentChild类。在子类中,我想实现一个弱类型字段,我可以在其中输入任何JSON值,只是一个常规的键/值存储。这是我的设置:

public class Child
{
public int Id { get; set; }
public string Type { get; set; }
public BsonDocument Properties { get; set; }
}
public class Parent
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public List<Child> Children { get; set; }
}

在数据库中,父元素可能如下所示:

{
"_id" : 1,
"Children" : [
{
"_id" : 1,
"Type" : "TEXT",
"Properties" : {
"Width" : 100,
"Height" : 100,
"Color" : "red"
}
}]
}

从数据库中读取就是这样工作的。MongoDB正在反序列化数据,一切正常。我遇到的问题出在控制器级别。这是相当简单的控制器代码:

[HttpGet]
public ActionResult<List<Parent>> Get()
{
// _parentRepository.Get() is returning a List<Parent> read from the DB
return _parentRepository.Get();
}

但是当我向 API 发送请求时,这就是我得到的结果:

{
"id" : 1,
"children" : [
{
"id" : 1,
"type" : "TEXT",
"properties" : [
{
"name": "Width",
"value": 100
},
{
"name": "Height",
"value": 100
},
{
"name": "Color",
"value": "red"
}
]
}]
}

如您所见,BsonDocument像字典一样序列化,其中它是键/值对的列表。我宁愿在那里有一个平面 JSON,所以表示形式与数据库中的表示形式完全相同。

我尝试使用JsonResult和显式强制转换来Controller.Json(),但结果是一样的。

注意:我正在使用.NET Core 2.2!我知道 3.0 引入了一些与 JSON 相关的更改,但尚未能够更新项目。

谢谢!

这只是Newtonsoft.JsonBsonDocument类型序列化为string的方式。您可以轻松解决此问题,引入自己的序列化程序并运行BsonDocument.ToJson()方法:

public class BsonToJsonConverter : JsonConverter<BsonDocument>
{
public override BsonDocument ReadJson(JsonReader reader, Type objectType, BsonDocument existingValue, bool hasExistingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
return BsonDocument.Parse(token.ToString());
}
public override void WriteJson(JsonWriter writer, BsonDocument value, JsonSerializer serializer)
{
writer.WriteRawValue(value.ToJson());
}
}

并装饰您的类型:

public class Child
{
public int Id { get; set; }
public string Type { get; set; }
[JsonConverter(typeof(BsonToJsonConverter))]
public BsonDocument Properties { get; set; }
}

最新更新