Convert MongoDB BsonDocument to valid JSON in C#

后端 未结 10 2542
旧巷少年郎
旧巷少年郎 2020-12-01 14:16

I am working with the MongoDB C# driver. I have a BsonDocument with some data which includes some MongoDB-specific types (like ObjectIDs and ISODates). I want t

相关标签:
10条回答
  • 2020-12-01 15:00

    MongoDB.Bson (2.5+) has support to map between BsonValues and .Net objects. BsonTypeMapper Class

    To map a BsonValue (or BsonDocument) to .Net object use

    var dotNetObj = BsonTypeMapper.MapToDotNetValue(bsonDoc);
    

    You can then use your choice of serialization library. For example,

    JsonConvert.SerializeObject(dotNetObj);
    

    If you have a List of BsonDocument

    var dotNetObjList = bsonDocList.ConvertAll(BsonTypeMapper.MapToDotNetValue);
    
    0 讨论(0)
  • 2020-12-01 15:00

    If the contents of the BSON document is saved as, below

    {
    "Date" : "2019-04-05T07:07:31.979Z",
    "BSONCONTENT" : {
        "_t" : "MongoDB.Bson.BsonDocument, MongoDB.Bson",
        "_v" : {
            "A" : "XXXX",
            "B" : 234   
               }  
     }     
    

    }

    then it works with generic class.

    private static T ProcessBsonConversion<T>(BsonDocument data)
        {
            var content = data.GetElement("_v");
            var jsonDataContent= content.Value.AsBsonValue.ToJson();
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonDataContent);
    
        }
    
    0 讨论(0)
  • 2020-12-01 15:07

    Most of the Time for this I use, Json.NET

    JsonConvert.SerializeObject(obj); 
    

    Most of the time that does the trick. If need be you can set some JsonSerializerSettings

    0 讨论(0)
  • 2020-12-01 15:08

    In my opinion the best option is to use Newtonsoft.Json.Bson.BsonReader. Here a complete example:

    public string ToJson(BsonDocument bson)
    {
        using (var stream = new MemoryStream())
        {
            using (var writer = new BsonBinaryWriter(stream))
            {
                BsonSerializer.Serialize(writer, typeof(BsonDocument), bson);
            }
            stream.Seek(0, SeekOrigin.Begin);
            using (var reader = new Newtonsoft.Json.Bson.BsonReader(stream))
            {
                var sb = new StringBuilder();
                var sw = new StringWriter(sb);
                using (var jWriter = new JsonTextWriter(sw))
                {
                    jWriter.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                    jWriter.WriteToken(reader);
                }
                return sb.ToString();
            }
        }
    }
    

    I think that this should handle all cases correctly (dates, ids, ...).

    0 讨论(0)
提交回复
热议问题