json.net似乎不想将guid序列化为本机bson uuids,而是将guids输出为字符串。
我已经测试了从JObject
生成BSON的生成BSON(在序列化之前验证JValue.Type == JTokenType.Guid
)和匿名类型(new { myUuid = new Guid() }
),在任何一种情况下都没有运气。
我如何将json.net强制为本机bson uuids序列化guid(16个字节二进制值; subtype = 0x04)?
示例代码:
var source = new
{
myInteger = 123L,
myFloat = 10.0f,
myString = "hello",
myUuid = Guid.NewGuid(),
myBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7 },
myDatetime = DateTime.UtcNow,
};
MemoryStream buffer = new MemoryStream();
BsonWriter writer = new BsonWriter(buffer);
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, source);
byte[] myBson = buffer.ToArray();
问题来自BsonWriter
上的WriteValue
的实现(版本4.5.0.0):
public override void WriteValue(Guid value)
{
base.WriteValue(value);
this.AddToken((BsonToken) new BsonString((object) value.ToString(), true));
}
注意第二行,它将Guid
写为字符串,这就是为什么您会看到结果。
使用以下示例:
[TestMethod]
public void TestMethod1()
{
var source = new
{
myUuid = Guid.NewGuid(),
};
using (var buffer = new MemoryStream())
using (var writer = new BsonWriter(buffer))
{
var serializer = new JsonSerializer();
serializer.Serialize(writer, source);
byte[] myBson = buffer.ToArray();
}
}
我希望从索引12开始的字节为(按照规格):