如何使用C#MsgPack反序列化[[doubles],[ints]]数组?

时间:2018-08-10 16:45:06

标签: c# .net arrays deserialization msgpack

所以msgpack-c为我提供了objects as arrays。说我像这样序列化了一条C ++消息:

template <class T>
        struct Message {
            std::vector<T> data;
            std::vector<int> shape; 
            MSGPACK_DEFINE(data, shape);
        };

并拥有T == double

如果在C ++中反序列化为json,它将具有[[1.23,3.01,44.02,33],[2,2]]之类的内部内容。

现在,我想在C# with MessagePack-CSharp中反序列化它。如果我尝试将其转换为json字符串,当我尝试

时会得到一个空字符串
var msg = MessagePackSerializer.Deserialize<List<List<double>>>(e.RawData);

我知道

  

System.InvalidOperationException:代码无效。代码:0   格式:正fixint位于   MessagePack.Decoders.InvalidArrayHeader.Read(System.Byte []个字节,   Int32偏移量,System.Int32&readSize)[0x0001b]在   MessagePack / MessagePackBinary.cs:3543

当我尝试时会发生同样的事情:

 [MessagePackObject]
    public class Msg {
        [Key(0)]
        public List<double> data;
            [Key(1)]
        public List<int> shape;
    }

那么如何在C#MessagePack-CSharp中反序列化[[doubles], [ints]]数组?

1 个答案:

答案 0 :(得分:0)

[MessagePackObject]
public class Msg
{
    [Key(0)]
    public List<double> data;
    [Key(1)]
    public List<int> shape;
}

static class Program
{
    static void Main(string[] args)
    {
        var bytes = MessagePackSerializer.Serialize(new Msg()
        {
            data = new List<double> { 1.23, 3.01, 44.02, 33 },
            shape = new List<int>() { 2, 2 }
        });
        var msg = MessagePackSerializer.Deserialize<Msg>(bytes);
        Console.WriteLine(MessagePackSerializer.ToJson(msg));
    }
}

应该完成工作并产生输出[[1.23,3.01,44.02,33],[2,2]]