Expand Object to Bson

Asked

Viewed 169 times

5

How can I build a parse expander Object for Bson? (Vs 2013 - C# - Mongodb)

  • The question is good. You have no problem with it.

  • I did jump for not knowing the subject, but it seemed to me ample of more.

  • Voting to reopen.

  • @Ciganomorrisonmendez sees if the question is better like this.

  • 1

    Yeah, it’s a little more objective. The question is actually very simple. Writing more would be sheer prolixity.

2 answers

7

For this case, the ideal would be an extension method more or less 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;
    }
}

Use:

var bsonEsperado = meuExpandoObject.ParaBsonDocument();
  • Good afternoon, Gypsy boy! I am having a small error in the line below: return[kvp.Key] = kvp.Value; Cannot implicity Convert type 'Object' to 'Mongodb.Bdon.Bsonvalue' Have you seen this error yet!?

  • Good solution Gypsy thank you very much I did not implement it exactly but I used the general idea!

  • @Luizrocha Would you like to answer with the result of its implementation? It could help other people who are having the same problem.

1


Good morning, folks! Thanks again for your help! I’m done using an external library very effective.

Note: I converted at the end to String only to perform 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;
        }
    }
}
  • 1

    Thanks Gypsy for adjusting the cog here! kkk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.