C# - BinaryFormatter.Deserialize 将一些值保留为 Byte[]

C# - BinaryFormatter.Deserialize leaves some values as Byte[]

编辑:我无法控制序列化,所以使用 json 不是一个选项。

我正在使用 BinaryFormatter 反序列化一个 Dictionary<string, object>。字典的简单表示是:

{
    "correlation_id": "7233bdc9-56d2-4f7a-96cf-14bb1d62ea82",
    "error": {
        "code": "openaccess.authentication.invalidinternallogin",
        "message": "The username/password combination you have entered is incorrect. Please make sure your username is correct and then retype your password."
        },
    "method": "add_authentication",
    "version": "1.0",
    "business_event_class": "Unknown"
}

唯一正确反序列化的键值对是最后一个 ("business_event_class"),因为双方都被转换为字符串。在所有其他情况下,包括嵌套字典 ("error"),键被转换为字符串,但值保持为 Byte[].

我的代码:

var mStream = new MemoryStream();
var binFormatter = new BinaryFormatter();
mStream.Write(binDict, 0, binDict.Length);  //binDict is the serialized dict
mStream.Position = 0;
var responseDict = binFormatter.Deserialize(mStream) as Dictionary<string, object>;

编码的 (base64) 字典对象是:

AAEAAAD/////AQAAAAAAAAAEAQAAAOIBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuRGljdGlvbmFyeWAyW1tTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uT2JqZWN0LCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQQAAAAHVmVyc2lvbghDb21wYXJlcghIYXNoU2l6ZQ1LZXlWYWx1ZVBhaXJzAAMAAwiSAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkdlbmVyaWNFcXVhbGl0eUNvbXBhcmVyYDFbW1N5c3RlbS5TdHJpbmcsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR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5hdGlvbiB5b3UgaGF2ZSBlbnRlcmVkIGlzIGluY29ycmVjdC4gUGxlYXNlIG1ha2Ugc3VyZSB5b3VyIHVzZXJuYW1lIGlzIGNvcnJlY3QgYW5kIHRoZW4gcmV0eXBlIHlvdXIgcGFzc3dvcmQuCw==

我注意到反序列化为 Byte[] 的值表示 ASCII 字符。使用 Encoding.UTF8.GetString 将它们转换为字符串的递归函数(反序列化字典具有嵌套字典)就成功了。