我将 mongodb 与 Rest 一起使用。每个文档都由一个字段Id(Guid)和Name(string)组成
这是我访问网页时显示的内容:
"_id" : { "$binary" : "Oq4RFClrRUOtIp89AQTGPw==",
"$type" : "03"
"name" : "HelloWorld"
在 mongodb 中,我的 Guid 被转换为 UUID(比如我的 JMongoBrowser)并显示为 46eb229f-b493-5630-b0d7-aa00499fafa0。
但是当我访问我的休息网页时,它被分成两部分(二进制和类型)。那么如何将其转换为 C# 对象?
谢谢
最佳答案
该字符串是表示guid字节数组的base-64编码字符串,但是需要处理字节UUD编码,所以可以这样取回:
public static Guid ToGuid(string jsonUuid)
{
byte[] bytes = Convert.FromBase64String(jsonUuid);
byte[] rbytes = new byte[16];
rbytes[0] = bytes[4];
rbytes[1] = bytes[5];
rbytes[2] = bytes[6];
rbytes[3] = bytes[7];
rbytes[4] = bytes[2];
rbytes[5] = bytes[3];
rbytes[6] = bytes[0];
rbytes[7] = bytes[1];
rbytes[8] = bytes[15];
rbytes[9] = bytes[14];
rbytes[10] = bytes[13];
rbytes[11] = bytes[12];
rbytes[12] = bytes[11];
rbytes[13] = bytes[10];
rbytes[14] = bytes[9];
rbytes[15] = bytes[8];
return new Guid(rbytes);
}
或者像这样:
public static Guid ToGuid(string jsonUuid)
{
return new Guid(Convert.FromBase64String(jsonUuid));
}
关于c# - 将 MongoDB Rest 的 Guid 转换为 C# CLR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7193041/