WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Json.Net Deserialize a Collection from BSON

Posted on 2023-12-21 15:43  WebEnh  阅读(2)  评论(0编辑  收藏  举报

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
}