当解压缩包含NULL作为项的可空整数列表时,C#MsgPack抛出

时间:2016-11-09 10:02:36

标签: c# json deserialization msgpack

我想使用MsgPack而不是Newtonsoft.JSON,因为它更快,但在尝试反序列化可以为空的整数列表时遇到问题。

以下是我正在使用的代码片段:

          public class MyClass
          {
                 public MyClass()
                 {
                       MyCustomList = new List<int?>();
                 }
                 public List<int?> MyCustomList { get; private set; }
          }


        MyClass source = new MyClass();
        source.MyCustomList.Add(1);
        source.MyCustomList.Add(null);

        var context = new SerializationContext {SerializationMethod = SerializationMethod.Map};
        context.DictionarySerlaizationOptions.OmitNullEntry = true;

        //Create serializers
        var serializer = SerializationContext.Default.GetSerializer<MyClass>(context);
        var serializerDest = SerializationContext.Default.GetSerializer<MyClass>(context);

        Stream stream = new MemoryStream();
        serializer.Pack(stream, source);
        stream.Position = 0;
        var unpackedObject = serializerDest.Unpack(stream); 

代码的最后一行是抛出类似“{”的异常。解压缩的值不是'System.Int32'类型。不要将nil MessagePackObject转换为System.Int32。“}”

我的'MyCustomList'属性属于List类型,不起作用。如果我切换到IList它可以工作

知道这是否是已知错误?我怎么能摆脱它?

由于

1 个答案:

答案 0 :(得分:0)

我正在使用MsgPack版本2.0.0-alpha2,它工作正常。 我做的只是我注释掉了这一行,因为这个版本的msgpack无法识别它。

// context.DictionarySerializationOptions.OmitNullEntry = true;

enter image description here

using System.IO;
//using Microsoft.VisualStudio.Modeling;
using MsgPack.Serialization;


namespace ConsoleApplicationTestCs
{
class Program
{
    static void Main(string[] args)
    {

    MyClass source = new MyClass();
    source.MyCustomList.Add(1);
    source.MyCustomList.Add(null);

    var context = new SerializationContext { SerializationMethod = SerializationMethod.Map };

    //context.DictionarySerializationOptions.OmitNullEntry = true;

    //Create serializers
    var serializer = SerializationContext.Default.GetSerializer<MyClass>(context);
    var serializerDest = SerializationContext.Default.GetSerializer<MyClass>(context);

    Stream stream = new MemoryStream();
    serializer.Pack(stream, source);
    stream.Position = 0;
    var unpackedObject = serializerDest.Unpack(stream);

}


}

public class MyClass
{
    public MyClass()
    {
        MyCustomList = new List<int?>();
    }
    public List<int?> MyCustomList { get; private set; }
}

}