c# - 将 MongoDB Rest 的 Guid 转换为 C# CLR

标签 c# mongodb mongodb-.net-driver

我将 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/

相关文章:

c# - 如何在启动时处理表单显示顺序

c# - 交易范围和交易

node.js - mongodb 不会启动 mongod -> error dbpath does not exists, but the path does exit

linux - 将所有图像放入数据库或文件夹中

c#-4.0 - 如何模拟 MongoDB 对象来测试我的数据模型?

MongoDb:如何使用 C# 官方驱动程序返回选择(查找)中的不同字段

c# - RSA 加密中的 fOAEP 参数

c# - 如何创建一个灵活的架构,使我能够在多个不同的底层数据模型上运行?

javascript - 更新 Mongo 文档内的数组不起作用

mongodb - 如何获取使用 MongoDB C# 驱动程序创建 MongoDB 集合的日期?