37

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 to convert this to a valid general-purpose JSON string. In other words, I can't have something like _id: ObjectId(...) or date: ISODate(...) but would prefer _id: "..." and date: "...". Basically, I want to convert these special types that only MongoDB recognizes to regular strings so they can be parsed more easily. The problem is that a built-in function like .ToJson() (which another StackOverflow answer suggests) doesn't really convert the document to valid JSON at all because it maintains these special types. My document also contains many levels of arrays and sub-documents, so a simple for loop will not suffice. What's the best way to convert a BsonDocument that avoids this problem? I would prefer something built-in rather than manually recursing through the document to fix all the issues.

2
  • 2
    I know right. Why would a method called ToJson() return something that is NOT standard Json.. So annoying. Although MarkKGreenway provides a great one liner solution using Newtonsofts API. I think his is the correct answer!
    – Piotr Kula
    Nov 22, 2018 at 11:36
  • 1
    The best answer is stackoverflow.com/a/55788508/2074346 Oct 4, 2020 at 3:36

11 Answers 11

46

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);
4
  • 2
    This answer is exactly on point. The issue here is converting the BSON document into an object that map's to DotNet.
    – FlyingV
    Jun 11, 2019 at 3:29
  • 3
    This was the answer. I have made numerous attempts at a solution to this issue that manifested in a few different ways, from the id to datetime types and this converts into Dot Net, and thus JSON the way you would expect. Excellent work, thank you. Jun 14, 2019 at 16:42
  • Interestingly enough, this is not comprehensive. A good chunk of the types will simply pass through unmapped. This one bit me when I was trying to map a regular expression to its pattern string. Had to do it manually. github.com/mongodb/mongo-csharp-driver/blob/…
    – Mike Loux
    Nov 4, 2020 at 16:14
  • Your solution works 100%! Thank you!
    – gideonlouw
    Aug 16 at 7:33
22

I've ran into the same thing, you can get valid JSON via:

var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
JObject json = JObject.Parse(postBsonDoc.ToJson<MongoDB.Bson.BsonDocument>(jsonWriterSettings));

However it will return something like:

{"_id":{"$oid":"559843798f9e1d0fe895c831"}, "DatePosted":{"$date":1436107641138}}

I'm still trying to find a way to flatten that.

5
11

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

4
  • Each line here is a potential bug.. MarkKGreenway provided a mega simple e one liner works as expected!
    – Piotr Kula
    Nov 22, 2018 at 11:34
  • @ppumkin If I remember correctly JsonConvert.SerializeObject will not correctly handle Guid or some other data types (datetime maybe ...). But I can be wrong ... Feb 26, 2019 at 17:56
  • Yes! I finally found something that works for me. Note that I had to add some using statements for MongoDB.Bson.IO (for the BsonBinaryWriter) and MongoDB.Bson.Serialization (for the BsonSerializer). I get a warning that Newtonsoft.Json.Bson.BsonReader has moved to its own package (Newtonsoft.Json.Bson), but I have included that package so I don't know why it is complaining. Jan 25, 2021 at 22:28
  • I also used a similar method to convert a BsonValue to JSON. Jan 25, 2021 at 22:54
8

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

3
  • Thank you! This should be the answer! -- I needed that for a customer BsonDocumentJson deserialiser i put in, which used the BsonDocument.ToJson() but returned crap like NumberDecimal("99.98") - I just replaced that with your line. Works great!!
    – Piotr Kula
    Nov 22, 2018 at 11:38
  • The best answer is stackoverflow.com/a/55788508/2074346 Oct 4, 2020 at 3:36
  • I get an error with the message: "Specified cast is not valid" so this option is not working for me for some reason. Since this answer was back in 2014, I suspect something has changed in MongoDB or in Json.Net (now Newtonsoft). Jan 25, 2021 at 22:09
7

Through experimentation I discovered that there is an option that makes this method output proper JSON:

BsonDocument myBsonDocument = ... //code that loads a BSON document
myBsonDocument.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.RelaxedExtendedJson})

Result:

{ "_id" : { "$oid" : "5fb7a33e73152101d6610e9d" }, "moreProperties" : "moreValues" }
2
  • 2
    Shame on MongoDB programmers for not making this the default output!
    – Jordi
    Nov 24, 2020 at 14:57
  • It's not the default because certain type information is lost when using RelaxedExtendedJson. Which is fine for most use cases, but not all.
    – Rudey
    Dec 23, 2022 at 9:14
2

Here is the way i did it, to skip mongodb _id entry.

var collection = _database.GetCollection<BsonDocument>("test");

var result = await collection.Find(new BsonDocument())
     .Project(Builders<BsonDocument>.Projection.Exclude("_id"))
     .ToListAsync();
var obj = result.ToJson();
1

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

    }
1

My problem had to do with how DotNet Core WebAPI serializes an object to json. If you return a string from a method that is formatted as json, WEBAPI will serialize it to json again. This is only needed if you are working with a generic BsonDocument to save to MongoDb.

[HttpGet()]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<string>> GetAsync()
{
    return Ok(ret.ToJson());
}

Fix

[HttpGet()]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<object>> GetAsync()
{
    var doc = await _collection.Find(...).FirstOrDefaultAsync();
    return Ok(JObject.Parse(doc.ToJson()));
}
1

Since Davide Icardi answer is deprecated so:

  1. Install Newtonsoft.Json.Bson package
  2. Replace BsonReader with BsonDataReader.

Your extension method should be like this:

using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System.IO;
using System.Text;

namespace YourNamespaceGoesHere
{
    public static class BsonHelpers
    {
        public static string ToNormalJson(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 BsonDataReader(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();
                }
            }

        }

    }
}

This should generate the expected normal valid JSON string you're looking for :)

0

If you need to use this ASP.NET Core for when you may be returning a model that has BsonDocument to be able to add dynamic data. You can use this JsonConverter implementation based on MarkKGreenway's answer!

 public class BsonDocumentJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(BsonDocument);
        }

        public override bool CanRead
        {
            get
            {
                return false;
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            //string json = (value as BsonDocument).ToJson(); //!NB: this returns BSON not JSON. Why on earth is it called ToJson!?
            string json = JsonConvert.SerializeObject(value);
            writer.WriteRawValue(json);
        }
    }

Then in your Startup.cs just add the following.

  services.AddMvc()
                .AddJsonOptions(options => options.SerializerSettings.Converters.Add(new BsonDocumentJsonConverter()));
0

what about

String json = result.toJson(JsonWriterSettings.builder().objectIdConverter(new Converter<ObjectId>() {
            @Override
            public void convert(ObjectId value, StrictJsonWriter writer) {
                writer.writeString(value.toHexString());
            }
        }).build());

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.