Json.Net Deserialize a Collection from BSON

发布时间 2023-12-21 15:45:27作者: WebEnh

Deserialize a Collection from BSON (newtonsoft.com)

This sample sets ReadRootValueAsArray to true so the root BSON value is correctly read as an array instead of an object and deserializes BSON to a collection.

Sample
Types
public class Event
{
    public string Name { get; set; }
    public DateTime StartDate { get; set; }
}
Usage
string s = "MQAAAAMwACkAAAACTmFtZQAHAAAARWFzdGVyAAlTdGFydERhdGUAgDf0uj0BAAAAAA==";
byte[] data = Convert.FromBase64String(s);

MemoryStream ms = new MemoryStream(data);
using (BsonReader reader = new BsonReader(ms))
{
    reader.ReadRootValueAsArray = true;

    JsonSerializer serializer = new JsonSerializer();

    IList<Event> events = serializer.Deserialize<IList<Event>>(reader);

    Console.WriteLine(events.Count);
    // 1

    Console.WriteLine(events[0].Name);
    // Easter
}