序列化List <dictionary <string,object>&gt;使用Protobuf-Net

时间:2015-11-06 12:58:37

标签: c# serialization protobuf-net

我有一个字典列表,我想序列化,但是我收到以下错误:

  

System.NotSupportedException不支持嵌套或锯齿状列表和数组

甚至可以将其序列化吗?我尝试将其推送到其他班级,并List<Dto> Dto班级为IEnumerable DictionaryDynamicType对于字典中的对象,但它仍然无法正常工作。 我是以完全错误的方式解决这个问题,还是我错过了一些微妙的东西?

示例代码:

var zone = DateTimeZoneProviders.Tzdb["Europe/London"];
        _testObj = new Person
        {
            Name = "Homer",
            Age = 38,
            Timestamp = new ZonedDateTime(Instant.FromUtc(2013, 6, 12, 17, 53, 23), zone),
            Target = new DataCollection(new Dictionary<string, Type>()
            {
                {"Date", typeof(DateTime)}

            }, new List<Dictionary<string, object>>
            {
                new Dictionary<string, object>
                {
                    {"Date", new DateTime(2015, 1, 1)}
                }
            }
            , new List<string> { "Date" })

DataCollection

[Serializable, ProtoContract(IgnoreListHandling = true), DataContract, JsonObject]
public class DataCollection : IEnumerable<IDictionary<string, object>>
{
    public DataCollection(Dictionary<string, Type> fields, List<Dictionary<string, object>> data, List<string> keyFields)
    {
        Fields = fields;
        KeyFields = keyFields;
        Data = data;
    }

    public DataCollection()
    {
        Fields = new Dictionary<string, Type>();
        Data = new List<Dictionary<string, object>>();
        KeyFields = new List<string>();
    }

    [ProtoMember(1), DataMember]
    public Dictionary<string, Type> Fields { get; set; }

    [ProtoMember(2), DataMember]
    public List<string> KeyFields { get; set; }

    [ProtoMember(3), DataMember]
    public List<Dictionary<string, object>> Data { get; set; }

    public void Add(Dictionary<string, object> value)
    {
        Data.Add(value);
    }

    public IEnumerator<IDictionary<string, object>> GetEnumerator()
    {
        return Data.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

如果我没有包含ProtoMember(3),我可以顺序完成。

1 个答案:

答案 0 :(得分:2)

所以问题归结为Protobuf-net,这是正确的,不喜欢字典中的对象类型。我不想详细说明为什么我需要它,只需说你需要使用2个代理类的组合,并且对象Type需要用BinaryFormatter序列化为byte []然后发送到Protobuf网,因为Protobuf规范不承认对象类型。

我正在从这个网站复制解决方案的灵感:http://rushfrisby.com/serializing-non-serializable-types-with-protobuf/

根据发布解决方案的规则而不是单独链接到外部网站:

以此课程为例:

[DataContract]
public class MyNameValueInfo
{
    [DataMember(Order = 1)]
    public string Name { get; set; }

    [DataMember(Order = 2)]
    public object Value { get; set; }
}

MyNameValueInfo无法序列化,因为它不知道如何序列化Value属性(typeof对象)。它将引发异常:“没有为类型定义Serializer:System.Object”

为了解决这个问题,我们需要提供protobuf-net可以序列化的MyNameValueInfo的代理。首先注册代理类型(只需要执行一次):

RuntimeTypeModel.Default.Add(typeof(MyNameValueInfo),false)。SetSurrogate(typeof(MyNameValueInfoSurrogate));

然后实现MyNameValueInfoSurrogate,以便它可以从/转换为MyNameValueInfo并且可以通过protobuf-net进行序列化:

[DataContract]
public class MyNameValueInfoSurrogate 
{
        //string is serializable so we'll just copy this property back and forth
    [DataMember(Order = 1)]
    public string Name { get; set; } 

        //byte[] is serializable so we'll need to convert object to byte[] and back again
    [DataMember(Order = 2)]
    public byte[] Value { get; set; }

    public static implicit operator MyNameValueInfo(MyNameValueInfoSuggorage suggorage)
    {
        return suggorage == null ? null : new MyNameValueInfo
        {
            Name = suggorage.Name,
            Value = Deserialize(suggorage.Value)
        };
    }

    public static implicit operator MyNameValueInfoSuggorage(MyNameValueInfo source)
    {
        return source == null ? null : new MyNameValueInfoSuggorage
        {
            Name = source.Name,
            Value = Serialize(source.Value)
        };
    }

    private static byte[] Serialize(object o)
    {
        if (o == null)
            return null;

        using (var ms = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, o);
            return ms.ToArray();
        }
    }

    private static object Deserialize(byte[] b)
    {
        if (b == null)
            return null;

        using (var ms = new MemoryStream(b))
        {
            var formatter = new BinaryFormatter();
            return formatter.Deserialize(ms);
        }
    }
}