msgpack / msgpack-cli

MessagePack implementation for Common Language Infrastructure / msgpack.org[C#]
http://msgpack.org
Apache License 2.0
835 stars 175 forks source link

how to serialize an object to string saved in redis and deserialize to an object #314

Closed xflag closed 5 years ago

xflag commented 5 years ago
using (var stream1 = new MemoryStream())
{
    SerializationContext ctx = new SerializationContext() { SerializationMethod = SerializationMethod.Map };
    var serializer1 = MessagePackSerializer.Get<P>(ctx);
    serializer1.Pack(stream1, new P() { Name = "Nesta",Team="Lazio" });
    stream1.Position = 0;
    var p1 = serializer1.Unpack(stream1);
    byte[] b = stream1.ToArray();
    string s = Encoding.ASCII.GetString(b);
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    var p2 = serializer1.Unpack(stream);
}
public class P
{
    public string Name { get; set; }
    public string Team { get; set; }
}

above code,p1 has correct value,but p2's property is null.Why?

yfakariya commented 5 years ago

As far as I understand, you tried to "decode" msgpack binary as ASCII string. So, AsciiEncoding could change the bytes their value are greater than 0x7F. So, variable s might be corrupted.

xflag commented 5 years ago

As far as I understand, you tried to "decode" msgpack binary as ASCII string. So, AsciiEncoding could change the bytes their value are greater than 0x7F. So, variable s might be corrupted.

en,how "decode" msgpack binary as string successfully?

joefeser commented 5 years ago

using (var stream1 = new MemoryStream()) { SerializationContext ctx = new SerializationContext() { SerializationMethod = SerializationMethod.Map }; var serializer1 = MessagePackSerializer.Get<P>(ctx); serializer1.Pack(stream1, new P() { Name = "Nesta",Team="Lazio" }); stream1.Position = 0; var p1 = serializer1.Unpack(stream1); byte[] b = stream1.ToArray(); MemoryStream stream = new MemoryStream(b); stream.Position = 0; var p2 = serializer1.Unpack(stream); }

xflag commented 5 years ago

I solve this problem,set byte[] to redis,don't convert to string.Tks.