Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 序列化列表/词典_C#_Serialization - Fatal编程技术网

C# 序列化列表/词典

C# 序列化列表/词典,c#,serialization,C#,Serialization,我有一个应用程序需要序列化一个自定义对象并将其发送到windows服务,该自定义对象包含两个自定义对象列表和一个int、string字典。当我尝试序列化对象时,收到错误消息: 生成XML文档时出错。 我在谷歌上搜索了一下,发现这通常是由于其中一个数据类型没有正确设置序列化。因此,我已经检查并验证了所有自定义类上的序列化,就我所知,它的设置是正确的 我现在的问题是,列表和字典在默认情况下是可以序列化的,还是需要做些什么来序列化它们?或者,有没有更好的方法来序列化要在可执行文件之间传递的自定义对象集

我有一个应用程序需要序列化一个自定义对象并将其发送到windows服务,该自定义对象包含两个自定义对象列表和一个int、string字典。当我尝试序列化对象时,收到错误消息:

生成XML文档时出错。

我在谷歌上搜索了一下,发现这通常是由于其中一个数据类型没有正确设置序列化。因此,我已经检查并验证了所有自定义类上的序列化,就我所知,它的设置是正确的

我现在的问题是,列表和字典在默认情况下是可以序列化的,还是需要做些什么来序列化它们?或者,有没有更好的方法来序列化要在可执行文件之间传递的自定义对象集合

编辑:

<MoveInInfoResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <RentalPeriods>
    <Item>
      <Key>
        <int>1</int>
      </Key>
      <Value>
        <string>Period 1</string>
      </Value>
    </Item>
    <Item>
      <Key>
        <int>2</int>
      </Key>
      <Value>
        <string>Period 2</string>
      </Value>
    </Item>
  </RentalPeriods>
</MoveInInfoResponse>
主要自定义类:

[Serializable]
class MoveInInfoRequest : ServerRequestData
{ }
[Serializable]
[XmlInclude(typeof(GetUnitTypesResponseData)), XmlInclude(typeof(VendorObj.RequiredFields)),
     XmlInclude(typeof(VendorObj.InsuranceChoice)), XmlInclude(typeof(VendorObj.ProrateSettings))]
public class MoveInInfoResponse : ServerResponseData
{
    public GetUnitTypesResponseData UnitTypesInfo
    { get; set; }
    public List<VendorObj.RequiredFields> RequiredFields 
    { get; set; }
    public Dictionary<int, String> RentalPeriods
    { get; set; }
    public List<VendorObj.InsuranceChoice> InsCoverageAmounts
    { get; set; }
    public VendorObj.ProrateSettings ProrateOptions
    { get; set; }
}
[可序列化]
类MoveInInfoRequest:ServerRequestData
{ }
[可序列化]
[xmlclude(typeof(getUnitTypesResponseTA)),xmlclude(typeof(VendorObj.RequiredFields)),
xmlclude(typeof(VendorObj.InsuranceChoice)),xmlclude(typeof(VendorObj.ProrateSettings))]
公共类MoveInInfoResponse:ServerResponseData
{
public GetUnitTypesResponseA UnitTypesInfo
{get;set;}
公共列表必填字段
{get;set;}
公共字典出租期
{get;set;}
公开名单
{get;set;}
public VendorObj.ProrateSettings ProrateOptions
{get;set;}
}
Sampple子类:其他两个类的设置与此类似,只是时间更长,但它们只使用默认数据类型

<Serializable(), DataContract([Namespace]:="*companyNamespace*")> _
Public Class InsuranceChoice
    Public Sub New()
    End Sub
    <DataMember()> _
    Public InsuranceChoiceID As Integer
    <DataMember()> _
    Public CoverageDescription As String
    <DataMember()> _
    Public Premium As Decimal
    <DataMember()> _
    Public ActualCoverageAmount As Decimal

End Class
_
公共类保险选择
公共分新()
端接头
_
公共保险选择ID为整数
_
公共覆盖范围描述为字符串
_
以十进制表示的公共保费
_
公共实际平均值(十进制)
末级

这取决于您试图用什么序列化它们。特别是,如果使用
XmlSerializer
,字典对象是不可序列化的,尽管如果使用
DataContractSerializer
,字典对象是可序列化的。可以序列化列表

如果您想要Xml序列化的替代方案,可以使用

参考资料:


这是一个非常常见的序列化问题

实现
IDictionary

您可以使用,但更好的解决方案(在我看来)是创建自己的Dictionary类,它不继承自
IDictionary

可以找到这样一个类的示例

在解决方案中实现类后,只需执行以下操作:

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var response = new MoveInInfoResponse
            {
                RentalPeriods = new SerializableDictionary<int, string> 
                { { 1, "Period 1" }, { 2, "Period 2" } }
            };

            string xml = Serialize(response);
        }

        static string Serialize(Object obj)
        {
            var serializer = new XmlSerializer(obj.GetType());
            var settings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true };

            using (var stream = new StringWriter())
            {
                using (var writer = XmlWriter.Create(stream, settings))
                    serializer.Serialize(writer, obj);
                return stream.ToString();
            }
        }
    }

    [Serializable]
    public class MoveInInfoResponse
    {
        public SerializableDictionary<int, String> RentalPeriods
        { get; set; }
    }
}
使用系统;
使用System.IO;
使用System.Xml;
使用System.Xml.Serialization;
命名空间控制台应用程序1
{
班级计划
{
静态void Main(字符串[]参数)
{
var响应=新的MoveInInfo响应
{
RentalPeriods=新的SerializableDictionary
{1,句点1},{2,句点2}
};
字符串xml=序列化(响应);
}
静态字符串序列化(对象obj)
{
var serializer=新的XmlSerializer(obj.GetType());
var settings=newXMLWriterSettings{Indent=true,ommitXMLDeclaration=true};
使用(var stream=new StringWriter())
{
使用(var writer=XmlWriter.Create(流、设置))
serializer.Serialize(writer,obj);
返回stream.ToString();
}
}
}
[可序列化]
公共类MoveInInfo响应
{
公共序列化字典RentalPeriods
{get;set;}
}
}
生成以下XML文件:

<MoveInInfoResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <RentalPeriods>
    <Item>
      <Key>
        <int>1</int>
      </Key>
      <Value>
        <string>Period 1</string>
      </Value>
    </Item>
    <Item>
      <Key>
        <int>2</int>
      </Key>
      <Value>
        <string>Period 2</string>
      </Value>
    </Item>
  </RentalPeriods>
</MoveInInfoResponse>

1.
第1期
2.
第2期

发布代码有助于获得答案:)它们是可序列化的,是的。正如@Mihai所说,代码会有所帮助。列表和字典是可以序列化的,您无需做任何事情。很明显,你是在把一些不存在的东西放进去,或者序列化一些不存在的东西。这个问题不是代码特定的,它更多的是供一般参考,因为我无法通过谷歌找到一个直接的答案。但是我添加了主类和其中一个子类,以防出现明显的错误…
我现在的问题是,列表和字典在默认情况下是否可以序列化,或者是否需要执行某些操作才能序列化它们
可以序列化的字段/属性是什么,取决于您使用的序列化程序。没有一般规则。例如,XmlSerializer不需要
Serializable
属性,它仅由BinaryFormatter使用(?),这是有意义的,因为我试图缩短rentalperiods对象,而不是编写新类。谢谢你的链接,他们让我明白了为什么我会有麻烦。谢谢你的帮助。这可能在将来派上用场。不过,对于这个实现来说,将有问题的datamember作为自己的类更为合理。