user996758
user996758

Reputation:

Serialize c# object using MsgPack instead of Json using MsgPack Cli

I'm trying to acheive a kind of JSON serialization using MsgPack in c# I'm using MsggPack CLI you can find on https://github.com/msgpack/msgpack-cli

According msgpack.org Documentation, serialize the model

{"model":"message"}

give in hexa

81 a5 6d 6f 64 65 6c a7 6d 65 73 73 61 67 65

but when trying to do the same in c# (certainly with a naive approach)

using MsgPack.Serialization;

public class Test
{
    public string model { get; set; }
}       

public class Program
{
    static void Main(string[] args)
    {
        Test a = new Test();
        a.model = "message";

        var requestSerializer = MessagePackSerializer.Get(a.GetType());
        MemoryStream stream = new MemoryStream();
        requestSerializer.Pack(stream, a);
        byte[] res = stream.ToArray();
    }
}

I obtain

91 a7 6d 65 73 73 61 67 65

where the 'model' name is skipped...

How to fix it ???

Upvotes: 2

Views: 3002

Answers (1)

user996758
user996758

Reputation:

Finally found the easy way. According to documentation, the serialization format is by default 'array' where i need 'map'. using

SerializationContext ctx = new SerializationContext() { SerializationMethod = SerializationMethod.Map };
...

var requestSerializer = MessagePackSerializer.Get(a.GetType(), ctx);

make the tricks.

Regards

Upvotes: 2

Related Questions