繁体   English   中英

mongodb C#驱动序列化model上的动态场

[英]mongodb C# driver serialize dynamic field on model

存在具有单个动态场的具体 model class。 该字段可能包含数百个 COMPLEX 数据结构,我们无法始终知道它们是什么。

public class Message {
    public dynamic MessageData { get; set; }
}

我们可以从 postman 中保存这个 json:

{
    "messageData": {
        "sdfghdfghjdfghdfg": {
            "sdfgsdfsdfghs": [
                {
                    "dfgfghkfghjfg": "4567456734573",
                    "dfjghjjkdehn": "fgjfghdfgjfhnfgh"
                }
            ],
            "hfgjkfguksdfgnuy": {}
        }
    }
  }

我们的 mongo find 方法显示了这个结果:

{
{ "_id" : ObjectId("607605a7d42ba9fa20579745"),
 "MessageData" : { "_t" : "Newtonsoft.Json.Linq.JArray, Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed", "_v" : [ { "_t" : "JObject", "_v" : [ { "_t" : "JProperty", "_v" : [ { "_t" : "JObject", "_v" : [ { "_t" : "JProperty", "_v" : [ { "_t" : "JArray", "_v" : [ { "_t" : "JObject", "_v" : [ { "_t" : "JProperty", "_v" : [ { "_t" : "JValue", "_v" : [ ] } ] }, { "_t" : "JProperty", "_v" : [ { "_t" : "JValue", "_v" : [ ] } ] } ] } ] } ] }, { "_t" : "JProperty", "_v" : [ { "_t" : "JObject", "_v" : [ ] } ] } ] } ] } ] } ] }
}

获取数据时,我们收到此错误:

System.FormatException: An error occurred while deserializing the MessageData property of class EMRPatientDB.Models.Message: Invalid element: '_t'.

问题似乎是 MongoDB C# 驱动程序没有正确序列化 JSON?

也许我们想编写一个自定义序列化程序? 但我还没有找到一个很好的例子来说明如何为 JSON object 做到这一点。

当我有一个具有 JObject 类型的属性的 C# JObject时遇到了这个问题。

我的解决方案是为 MondoDB 创建JObjectSerializer并将属性添加到属性中,以便 Mongo 序列化程序使用它。 我假设如果我足够努力,我也可以在 Mongo 中将以下序列化程序注册为这种类型的全局序列化程序。

注册序列化器进行属性处理:

[BsonSerializer(typeof(JObjectSerializer))]
public JObject AdditionalData { get; set; }

序列化程序本身:

public class JObjectSerializer : SerializerBase<JObject> // IBsonSerializer<JObject>
{
    public override JObject Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var myBSONDoc = BsonDocumentSerializer.Instance.Deserialize(context);
        return JObject.Parse(myBSONDoc.ToString());
    }

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, JObject value)
    {
        var myBSONDoc = MongoDB.Bson.BsonDocument.Parse(value.ToString());
        BsonDocumentSerializer.Instance.Serialize(context, myBSONDoc);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM