我的MongoDB驱动程序有问题。我正在编写一个JavaScript前端使用的.Net Core Web API。有Parent
和Child
类。在子类中,我想实现一个弱类型的字段,在其中可以放入任何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正在反序列化数据,一切正常。我遇到的问题是在控制器级别。那是相当简单的Controller代码:
[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.Json
将BsonDocument
类型序列化为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; }
}