简体   繁体   English

DataContractSerializer序列化列表 <T> 得到错误

[英]DataContractSerializer serializing List<T> getting error

I am currently trying to serialize a List, it serializes (I think fine), but when it deserialize, 我目前正在尝试序列化List,它序列化(我认为很好),但是当它反序列化时,

Sorry for the amount of code, but I am really stuck and have no idea why this is happening, i also tried to changed the struct into a class and no help. 很抱歉代码的数量,但我真的卡住了,不知道为什么会发生这种情况,我也试图将结构改成一个类而没有帮助。

THANKS. 谢谢。

i get the following error UPDATED 我得到以下错误更新

    There was an error deserializing the object of type There was an error deserializing the object of type 
`System.Collections.Generic.List`1[[A.B.C.DataValues, A.V, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]. Unexpected end of file. Following elements are not closed: Time, DataValues, ArrayOfDataValues.`

I am serializing like this UPDATED 我像这样更新了序列化

     public void SerializeDataValue(List<DataValues> values)
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(List<DataValues>));

                using (MemoryStream stream = new MemoryStream())
                {
                    using (GZipStream compress = new GZipStream(stream, CompressionMode.Compress))
                    {
                        XmlDictionaryWriter w = XmlDictionaryWriter.CreateBinaryWriter(compress);
                        serializer.WriteObject(w, values);

                    }
                    _serializedData = stream.ToArray();
                }
            }

I am deserializing like this UPDATED 我像这样更新了反序列化

 public List<DataValues> DeserializeDataValue()
{
    if (SerializedData == null || SerializedData.Length == 0)
    {
        return new List<DataValues> ();
    }
    else
    {
        DataContractSerializer serializer = new DataContractSerializer(typeof(List<DataValues>));
        using (MemoryStream stream = new MemoryStream(SerializedData))
        {
            using (GZipStream decompress = new GZipStream(stream, CompressionMode.Decompress))
            {
                XmlDictionaryReader r = XmlDictionaryReader.CreateBinaryReader(decompress, XmlDictionaryReaderQuotas.Max);
                return serializer.ReadObject(r, true) as List<DataValues>;
            }
        }
    }
}

Properties 属性

private byte[] _serializedData;

[DataMember]
[Browsable(false)]
public byte[] SerializedData
{
    get { return _serializedData; }
    set { _serializedData = value; }
}

helper Methods 帮助方法

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16 * 1024];
    input.Position = 0;
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

Struct 结构

[DataContract(Name = "DataValues", Namespace = "A.B.C")]
public struct DataValues
{
    [DataMember]
    public DateTime Time { get; set; }
    [DataMember]
    public Single Value { get; set; }

    public DataValues(DateTime dateTime, Single value)
    {
        Time = dateTime;
        Value = value;
   }
} 

It's because you are not serialising the object(s) completely. 这是因为你没有完全序列化对象。 You need to close the stream(s) after writing, especially when using gzip. 您需要在写入后关闭流,尤其是在使用gzip时。 Recommended practice is to use using : 建议的做法是using

public void SerializeDataValue(List<DataValues> values)
{
    DataContractSerializer serializer = new DataContractSerializer(typeof(List<DataValues>));
    using (MemoryStream stream = new MemoryStream())
    {
        using (GZipStream compress = new GZipStream(stream, CompressionMode.Compress))
        {
            XmlDictionaryWriter w = XmlDictionaryWriter.CreateBinaryWriter(compress);
            serializer.WriteObject(w, values);
        }
        _serializedData = stream.ToArray();
    }
}

Sorry to be late to this question. 很抱歉这个问题迟到了。

The problem with the initial approach was simply that you weren't flushing (read: disposing) the XmlDictionaryWriter . 初始方法的问题只是你没有刷新(读取:处理) XmlDictionaryWriter

This should work (note the 2nd using clause): 这应该工作(注意第二个使用条款):

using (GZipStream compress = new GZipStream(stream, CompressionMode.Compress))
using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateBinaryWriter(compress))
{
    serializer.WriteObject(w, values);
}

Hope this helps someone. 希望这有助于某人。

I can get the sample to work by removing the XmlDictionaryReader and instead directly feeding the input/output stream into the DataContractSerializer. 我可以通过删除XmlDictionaryReader并将输入/输出流直接输入DataContractSerializer来使样本工作。 It may be a defect in the XmlDictionaryReader for large compressed collections but I'm not sure. 对于大型压缩集合,它可能是XmlDictionaryReader中的缺陷,但我不确定。

Hope this helps: 希望这可以帮助:

public void SerializeDataValue(List<DataValues> values)
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(List<DataValues>));
                    using (MemoryStream stream = new MemoryStream())
                {
                    using (GZipStream compress = new GZipStream(stream, CompressionMode.Compress))
                    {
                        serializer.WriteObject(compress , values);

                    }
                    _serializedData = stream.ToArray();
                }
            }

    public List<DataValues> DeserializeDataValue()
    {
        if (SerializedData == null || SerializedData.Length == 0)
        {
            return new List<DataValues> ();
        }
        else
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(List<DataValues>));
            using (MemoryStream stream = new MemoryStream(SerializedData))
            {
                using (GZipStream decompress = new GZipStream(stream, CompressionMode.Decompress))
                {
                    return serializer.ReadObject(decompress , true) as List<DataValues>;
                }
            }
        }
    }

I ran exactly into the same problem and I finally found the solution : the XmlDictionaryWriter needs to be disposed/closed before the Stream you are writing into is itself closed. 我完全遇到了同样的问题,我终于找到了解决方案:XmlDictionaryWriter需要在你写入的Stream之前处理/关闭。 I discovered that thanks to the thorough example found at http://www.albahari.com/nutshell/ch15.aspx whiche are more complete than the MSDN ones. 我发现,多亏了http://www.albahari.com/nutshell/ch15.aspx上的详尽示例,这些示例比MSDN更完整。

In your sample code, that would be : 在您的示例代码中,这将是:

            using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateBinaryWriter(compress))
            {
                serializer.WriteObject(w, values);
            }

On my own example, using the XmlDictionaryWriter instead of the plain and by default Xml writer only gave me a ~25% decrease in file size but a factor 3 when reading back the object. 在我自己的例子中,使用XmlDictionaryWriter而不是普通的默认Xml编写器只能使文件大小减少约25%,但读回对象时减少了3倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM