将MongoDB Rest的Guid转换为C#CLR

Joh*_*ohn 1 c# mongodb mongodb-.net-driver

我在Rest上使用mongodb。每个文档都由一个字段Id(Guid)和Name(字符串)组成

这是我访问网页时显示的内容:

"_id" : { "$binary" : "Oq4RFClrRUOtIp89AQTGPw==",
        "$type" : "03"
"name" : "HelloWorld"
Run Code Online (Sandbox Code Playgroud)

在mongodb中,我的Guid转换为UUID(例如,我的JMongoBrowser),并显示为46eb229f-b493-5630-b0d7-aa00499fafa0。

但是,当我访问其余网页时,它被分为两部分(二进制文件和一种类型)。那么如何将其转换为C#对象呢?

谢谢

Sim*_*ier 5

该字符串是表示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);
}
Run Code Online (Sandbox Code Playgroud)

或像这样:

public static Guid ToGuid(string jsonUuid)
{ 
    return new Guid(Convert.FromBase64String(jsonUuid));
}
Run Code Online (Sandbox Code Playgroud)