无法将 MessagePack 反序列化回 JSON

Cannot deserialize MessagePack back to JSON

在数据库列中,存储了使用 ygoe/msgpack.js JavaScript 库序列化的 JSON 字节。

在 C# 中,我使用 neuecc/MessagePack-CSharp 库将此值反序列化为 JSON:

//From database (bytes generated from JavaScript ygoe/msgpack.js)
var bytes = connection.Query<byte[]>(sql).FirstOrDefault(); //Size: 11160 - Get bytes from database
var hexa = System.Text.Encoding.UTF8.GetString(bytes);  //=> Value: 8ca76...
var hexaString = FromHexString(hexa);   //=> Value: ��meeting��id�[=11=]\r�ۭmeetingNumber�2018194530...
var test1 = MessagePackSerializer.Deserialize<dynamic>(bytes);  //=> Value: 56
var test2 = MessagePackSerializer.Deserialize<RootObject>(bytes);  //=> System.InvalidOperationException: 'code is invalid. code:56 format:positive fixint'
var test3 = MessagePackSerializer.ToJson(bytes);    //=> Value:      "56"

//Manually
var jsonTest = "...JSON data..."; //Paste hexa on an online tool and use associated JSON (https://toolslick.com/conversion/data/messagepack-to-json#)
var test4 = MessagePackSerializer.Serialize(json);  //Size: 10893
var test5 = MessagePackSerializer.Deserialize<dynamic>(test4);  //OK
var test6 = MessagePackSerializer.Deserialize<RootObject>(test4);  //System.InvalidOperationException: 'code is invalid. code:218 format:str 16'

var test7 = MessagePackSerializer.FromJson(json);   //Size: 5928
var test8 = MessagePackSerializer.ToJson(test7);    //OK

正如您在上面看到的,我尝试了几种反序列化方法并且 none 成功了。我经常在输出中得到 56 或 218,但我的 JSON 不包含此值。我尝试了所有解析器,其中 none 有效。

然而,当 copy/pasting this website 上的十六进制时,我能够得到 JSON,这意味着数据库中的字节似乎有效。

知道哪里出了问题吗?

解决方案是转换为 HEX UTF8,然后再转换回 byte[]

代码:

public RootObject Deserialize(byte[] bytes)
{
    var hexUtf8 = Encoding.UTF8.GetString(bytes);
    var bytesUtf8 = HexStringToByteArray(hexUtf8);

    var serializer = MessagePackSerializer.Get<RootObject>();
    var stream = new MemoryStream(bytesUtf8);
    return serializer.Unpack(stream);
}

public static byte[] HexStringToByteArray(this string hex)
{
    var result = new byte[hex.Length / 2];
    for (var i = 0; i < result.Length; i++)
    {
        result[i] = System.Convert.ToByte(hex.Substring(i * 2, 2), 16);
    }
    return result;
}