首页 新闻 会员 周边

MongoDB.Bson 是否兼容 Newtonsoft.Json.Bson

0
悬赏园豆:30 [已解决问题] 解决于 2024-02-22 21:39

准备将 EnyimMemcachedCore 中使用的 Newtonsoft.Json.Bson 换成 MongoDB.Bson,请问 Newtonsoft.Json.Bson 序列化的内容是否可以被 MongoDB.Bson 反序列化?

dudu的主页 dudu | 高人七级 | 园豆:31048
提问于:2024-02-22 15:34
< >
分享
最佳答案
0

是兼容的,参考 MongoDB.Bson 的测试代码 BsonSerializerTests.cs#L77 ,用下面的代码验证通过

var employee = new Employee { FirstName = "John", LastName = "Smith", DateOfBirth = new DateTime(2001, 2, 3) };

var mongoBson = employee.ToBson();

using (var ms = new MemoryStream())
{
    using var writer = new BsonDataWriter(ms);
    var serializer = new JsonSerializer();
    serializer.Serialize(writer, employee);
    var NewtonsoftBson = ms.ToArray();

    var rehydrated = BsonSerializer.Deserialize<Employee>(NewtonsoftBson);
    Console.WriteLine(rehydrated.FirstName + " " + rehydrated.LastName);
}

using (var ms = new MemoryStream(mongoBson))
{
    using var reader = new BsonDataReader(ms);
    var serializer = new JsonSerializer();
    var rehydrated = serializer.Deserialize<Employee>(reader);
    Console.WriteLine(rehydrated.FirstName + " " + rehydrated.LastName);
}

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
}
dudu | 高人七级 |园豆:31048 | 2024-02-22 21:39

用 MongoDB.Bson 序列化与反序列化,代码比 Newtonsoft.Json.Bson 简洁

序列化

var bson = employee.ToBson();

反序列化

var employee = BsonSerializer.Deserialize<Employee>(NewtonsoftBson);
dudu | 园豆:31048 (高人七级) | 2024-02-23 07:37

在实现使用时发现还是存在一些兼容问题,比如:

dudu | 园豆:31048 (高人七级) | 2024-02-23 17:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册