How can I build a parse
Expanding Object
to Bson? (Vs 2013 - C # - MongoDB)
How can I build a parse
Expanding Object
to Bson? (Vs 2013 - C # - MongoDB)
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;
}
}
}
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();