Expando Object for Bson

5

How can I build a parse Expanding Object to Bson? (Vs 2013 - C # - MongoDB)

    
asked by anonymous 29.04.2015 / 16:04

2 answers

1

Good day, people! Thanks again for your help! I've done using an external library very effectively.

Note: I converted at the end to String just to run some tests.

using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;        

namespace xml
{ 
     class xmlParse
     {
       public static string object_2_Bson(ExpandoObject obj)
        {
            MemoryStream ms = new MemoryStream();
            using (BsonWriter writer = new BsonWriter(ms))
               {
                 JsonSerializer serializer = new JsonSerializer();
                 serializer.Serialize(writer, obj);
               }
            string bsonString = Convert.ToBase64String(ms.ToArray());
            return bsonString;
        }
    }
}
    
04.05.2015 / 15:49
7

For this case, the ideal would be an extension method something like this:

public static class BsonExtensions 
{
    public static BsonDocument ParaBsonDocument(this ExpandoObject obj) 
    {
        var retorno = new BsonDocument();

        foreach (KeyValuePair<string, object> kvp in obj) 
        {
            retorno[kvp.Key] = kvp.Value;
        }

        return retorno;
    }
}

Usage:

var bsonEsperado = meuExpandoObject.ParaBsonDocument();
    
29.04.2015 / 17:44