0

I want to convert an objeect of byte[][] type to Dictonary.

It always give an error "End of Stream encountered before parsing was completed."

Please help me .

 public static object ByteToObjectArray(byte[][] ms)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream mStream = new MemoryStream();
        mStream.Write(ms, 0, (int)ms.Length);
        mStream.Position = 0;
        return formatter.Deserialize(mStream) as object;

    }
xanatos
  • 109,618
  • 12
  • 197
  • 280
Vivek Verma
  • 293
  • 3
  • 16
  • 1
    `var d = Encoding.ASCII.GetBytes(ms.ToString());` I don't know what you are trying to do, but this line is sooo much wrong and without meaning... – xanatos Mar 16 '17 at 13:09
  • Now, count until 10 and then try to explain how a `byte[][]`, a `Dictionary`, an `Encoding.ASCII` and a `BinaryFormatter` should be used together to create a ??? (unclear what) – xanatos Mar 16 '17 at 13:16
  • my mistake. i have changed the code. – Vivek Verma Mar 16 '17 at 13:32
  • The code doesn't explain anything. What is in that array of buffers and what logic would convert any of them to a Dictionary of .... what? Why use a `BinaryFormatter` at all? – Panagiotis Kanavos Mar 16 '17 at 13:34
  • Before writing a deserializer, show us how the deserializer should work... You have a `Dictionary`... From here how should you arrive to a `byte[][]`? Where are the keys? Where are the values? – xanatos Mar 16 '17 at 13:38
  • @xanatos , Hi, am using redis cache. In that , HgetAll function returns the output as Byte[][] . The out is basically a list of object. So, now to use it , i have to convert it into dictionary type to make use of it. I am able to do conversion from byte[] to object. But unable to do with byte[][] . If you have any idea or an approach please help me out. – Vivek Verma Mar 17 '17 at 04:46

1 Answers1

0

The HGETALL should return the data as

key1
data1
key2
data2
...

So interleaved... Now... Supposing the key is in UTF8:

public static Dictionary<string, object> ByteToObjectArray(byte[][] bytes)
{
    var dict = new Dictionary<string, object>();
    var formatter = new BinaryFormatter();

    for (int i = 0; i < bytes.Length; i += 2)
    {
        string key = Encoding.UTF8.GetString(bytes[i]);
        // Alternatively
        //string key = Encoding.Unicode.GetString(bytes[i]);

        using (var stream = new MemoryStream(bytes[i + 1]))
        {
            object obj = formatter.Deserialize(stream);

            dict.Add(key, obj);
        }
    }

    return dict;
}
xanatos
  • 109,618
  • 12
  • 197
  • 280