在数据库列中,存储了使用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�\0\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
正如您在上面看到的,我尝试了几种反序列化的方法,但都没有效果。我的输出通常为56或218,但我的JSON不包含此值。我尝试了所有解析器,但没有一个起作用。
但是,当在this website上复制/粘贴十六进制时,我能够获取JSON,这意味着数据库中的字节似乎有效。
有什么主意吗?
答案 0 :(得分:0)
解决方案是先转换为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;
}