【问题标题】:C# MsgPack throws when unpack list of nullable integers containing a NULL as itemC# MsgPack 在解包包含 NULL 作为项目的可空整数列表时抛出
【发布时间】:2016-11-09 10:02:36
【问题描述】:

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

这是我正在使用的代码的 sn-p:

          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 它可以工作

知道这是否是已知错误吗?我怎样才能摆脱它?

谢谢

【问题讨论】:

  • 能否请您包含您的“MyClass”实现?
  • 我已经添加了类实现。
  • 它有一个拼写错误。 context.DictionarySerlaizationOptions.OmitNullEntry = true;另外,您使用的是哪个版本的 SerializationContext,因为在 vs2015 中它看起来非常不同。我以为我会运行此代码并查看您的错误,但所需的实现 vs2015 看起来非常不同:/ 所以我无法到达您遇到错误的地步。
  • Ahmm 你用的是哪个版本的 MsgPack?
  • 排序 :) .....

标签: c# json deserialization msgpack


【解决方案1】:

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

//context.DictionarySerializationOptions.OmitNullEntry = true;

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; }
}

}

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    相关资源
    最近更新 更多