GPGVM
GPGVM

Reputation: 5619

Turn BsonArray into List<T>

I've been working at this and have managed to get the json parsed into a C# object. Now the next step was to parse a json array into a List. I have managed to get the job done but I'm pretty sure there is a better way to convert from BsonArray to a List

using (StreamReader file = File.OpenText(filename))
{
   try
   {
      //first up convert to bson
      var jsonSampleData = file.ReadToEnd();

      //var bsonSampleData = BsonDocument.Parse(jsonSampleData); 
      //this would be for a single BSOnDocument

      var bsonSampleData = BsonSerializer.Deserialize<BsonArray>(jsonSampleData);
       var x = bsonSampleData.ToList();

       List<ThePlan> lst = new List<ThePlan>();

       foreach (var doc in x)
       {
          var t = BsonSerializer.Deserialize<ThePlan>(doc.AsBsonDocument);
          lst.Add(t);
       }

    }
    catch (Exception ex)
    {
       throw;
    }

Edit-Additional Information

To be clear what I am needing to accomplish is taking the given json document and rehydrate it to List. This is further complicated by my being new to mongo and T is a mongo entity representation.


As Andrei pointed out it works fine:

using (StreamReader file = File.OpenText(filename))
{
   var jsonSampleData = file.ReadToEnd();                    
   _thePlan = BsonSerializer.Deserialize<List<ThePlan>>(jsonSampleData);
}

Thinking about my struggles yesterday I think it actually had to do with my json where on my early attempts it looked like this:

{
   "_id": "57509afbc6b48d3f33b2dfcd",
   ...
}

In the process of figuring it all out my json matured to:

{
   "_id": { "$oid": "57509afbc6b48d3f33b2dfcd" },
   .....
}

The troubles I was having with BsonSerializer was likely my bad json and once that was worked out I wasn't astute enough to go back to the BsonSerielizer and try again.

Upvotes: 3

Views: 9749

Answers (1)

andrei.ciprian
andrei.ciprian

Reputation: 3025

Either go strongly typed all the way or not typed at all.

strongly typed

Assuming these are your types:

public class BaseObject {
  [BsonId] public ObjectId id { get; set; }
  [BsonElement("plans")] public List<ThePlan> Plans { get; set; }
}
public class ThePlan {
  [BsonElement("i")] public int Integer { get; set; }
  [BsonElement("s")] public string String { get; set; }
}

and these test utilities:

void ToJsonTyped(BaseObject bo)
{
  var sb = new StringBuilder();
  using (TextWriter tw = new StringWriter(sb))
  using (BsonWriter bw = new JsonWriter(tw)) 
  {
    BsonSerializer.Serialize<BaseObject>(bw, bo);
  }
  string jsonObject = sb.ToString();
  BaseObject bo2 = BsonSerializer.Deserialize<BaseObject>(jsonObject);
  Assert.AreEqual(bo, bo2);
}

void ToBsonTyped(BaseObject bo)
{
  byte[] bsonObject = null;
  using (var ms = new MemoryStream())
  using (BsonWriter bw = new BsonBinaryWriter(ms))
  {
    BsonSerializer.Serialize<BaseObject>(bw, bo);
    bsonObject = ms.ToArray();
  }
  BaseObject bo1 = BsonSerializer.Deserialize<BaseObject>(bsonObject);
  Assert.AreEqual (bo, bo1);
}

you can test:

  BaseObject bo = new BaseObject() {
    Plans = new List<ThePlan>() {
    new ThePlan() {Integer=1, String="one" },
    new ThePlan() {Integer=2, String="two" },
    new ThePlan() {Integer=3, String="three" } } };
  ToBsonTyped(bo);
  ToJsonTyped(bo);

not typed at all, combo of BsonDocument and BsonArray

test:

  BsonDocument doc = new BsonDocument();
  var bsonArray = new BsonArray();
  bsonArray.Add(new BsonDocument("one", 1));
  bsonArray.Add(new BsonDocument("two", 2));
  bsonArray.Add(new BsonDocument("three", 3));
  doc.Add( new BsonElement("plans", bsonArray));
  ToBsonUnTyped(doc);
  ToJsonUnTyped(doc);

test utils:

void ToBsonUnTyped(BsonDocument doc) {
  byte[] bsonObject = null;
  using (var ms = new MemoryStream())
  using (BsonWriter bw = new BsonBinaryWriter(ms))
  {
    BsonSerializer.Serialize<BsonDocument>(bw, doc);
    bsonObject = ms.ToArray();
  }
  BsonDocument docActual = BsonSerializer.Deserialize<BsonDocument>(bsonObject);
  Assert.AreEqual (doc, docActual);
}

void ToJsonUnTyped(BsonDocument doc)
{
  var sb = new StringBuilder();
  using (TextWriter tw = new StringWriter(sb))
  using (BsonWriter bw = new JsonWriter(tw))
  {
    BsonSerializer.Serialize<BsonDocument>(bw, doc);        
  }
  string jsonObject = sb.ToString();
  BsonDocument doc2 = BsonSerializer.Deserialize<BsonDocument>(jsonObject);
  Assert.AreEqual(doc, doc2);
}

Upvotes: 2

Related Questions