准备将 EnyimMemcachedCore 中使用的 Newtonsoft.Json.Bson 换成 MongoDB.Bson,请问 Newtonsoft.Json.Bson 序列化的内容是否可以被 MongoDB.Bson 反序列化?
是兼容的,参考 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; }
}
用 MongoDB.Bson 序列化与反序列化,代码比 Newtonsoft.Json.Bson 简洁
序列化
var bson = employee.ToBson();
反序列化
var employee = BsonSerializer.Deserialize<Employee>(NewtonsoftBson);
在实现使用时发现还是存在一些兼容问题,比如: