简体   繁体   English

如何序列化列表 <List<object> &gt;?

[英]How to serialize List<List<object>>?

Framework is c# .net 4.6.2 框架是c#.net 4.6.2

I am generating automatic XML classes from XML codes 我正在从XML代码生成自动XML类

When I auto generate, it automatically converts as Array[][] 当我自动生成时,它会自动转换为Array[][]

But i want to use it as List<List<>> 但我想将其用作List<List<>>

And i am sure that my conversation from Array to List causes some serialization error. 而且我确信从Array到List的对话会导致一些序列化错误。 I think it is about get and set functions. 我认为这与获取和设置功能有关。 So i need your help to fix this issue 因此,我需要您的帮助来解决此问题

Here the auto generated code piece when i edit > paste special > paste XML as classes 这是我编辑>粘贴特殊>将XML粘贴为类时自动生成的代码段

    /// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OxFordDefinition_perGroup
{

    private string _GroupDescField;

    private string _GroupSenseField;

    private string _GroupGrammerField;

    private OxFordDefinition_perGroup_perMainExample_perSubExample[][] _perMainExampleField;

    /// <remarks/>
    public string _GroupDesc
    {
        get
        {
            return this._GroupDescField;
        }
        set
        {
            this._GroupDescField = value;
        }
    }

    /// <remarks/>
    public string _GroupSense
    {
        get
        {
            return this._GroupSenseField;
        }
        set
        {
            this._GroupSenseField = value;
        }
    }

    /// <remarks/>
    public string _GroupGrammer
    {
        get
        {
            return this._GroupGrammerField;
        }
        set
        {
            this._GroupGrammerField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("_perSubExample", typeof(OxFordDefinition_perGroup_perMainExample_perSubExample), IsNullable = false)]
    public OxFordDefinition_perGroup_perMainExample_perSubExample[][] _perMainExample
    {
        get
        {
            return this._perMainExampleField;
        }
        set
        {
            this._perMainExampleField = value;
        }
    }
}

But instead of arrays, i want to use List<List<>> 但是我想使用List<List<>>而不是数组

So i make it like below 所以我像下面这样

        /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class OxFordDefinition_perGroup
    {

        private string _GroupDescField;

        private string _GroupSenseField;

        private string _GroupGrammerField;

        private  List<List<OxFordDefinition_perGroup_perMainExample_perSubExample>> _perMainExampleField;

        /// <remarks/>
        public string _GroupDesc
        {
            get
            {
                return this._GroupDescField;
            }
            set
            {
                this._GroupDescField = value;
            }
        }

        /// <remarks/>
        public string _GroupSense
        {
            get
            {
                return this._GroupSenseField;
            }
            set
            {
                this._GroupSenseField = value;
            }
        }

        /// <remarks/>
        public string _GroupGrammer
        {
            get
            {
                return this._GroupGrammerField;
            }
            set
            {
                this._GroupGrammerField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("_perSubExample", typeof(OxFordDefinition_perGroup_perMainExample_perSubExample), IsNullable = false)]
        public List<List<OxFordDefinition_perGroup_perMainExample_perSubExample>> _perMainExample
        {
            get
            {
                return this._perMainExampleField;
            }
            set
            {
                this._perMainExampleField = value;
            }
        }
    }

But this time it gives serialization error when i try to serialize like below 但是这一次当我尝试如下序列化时,它给出了序列化错误

       public static string SerializeXML<T>(this T toSerialize)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringWriter textWriter = new StringWriter();
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }

Here the full code of the XML class 这里是XML类的完整代码

http://pastebin.com/y5B8ENM3 http://pastebin.com/y5B8ENM3

Here the error it gives 这里给出的错误

在此处输入图片说明

Actually neither your original nor your modified OxFordDefinition_perGroup can be serialized successfully. 实际上,原始的或修改的OxFordDefinition_perGroup都无法成功序列化。 The problem is your value for XmlArrayItem.Type , which is the second argument to the constructor : 问题是您的XmlArrayItem.Type值是构造函数的第二个参数:

[System.Xml.Serialization.XmlArrayItemAttribute("_perSubExample", typeof(OxFordDefinition_perGroup_perMainExample_perSubExample), IsNullable = false)]
public OxFordDefinition_perGroup_perMainExample_perSubExample[][] { get; set; }

According to the docs 根据文档

Use the Type property to specify an overridden type for a public field or public read/write property value. 使用Type属性为公共字段或公共读/写属性值指定重写的类型。

If a field or property returns an array of type Object, apply multiple instances of the XmlArrayItemAttribute to the field or property. 如果字段或属性返回对象类型的数组,则将XmlArrayItemAttribute多个实例应用于该字段或属性。 For each instance, set the Type property to a type of object that can be inserted into the array. 对于每个实例,将Type属性设置为可以插入数组的对象的类型。

The typeof(OxFordDefinition_perGroup_perMainExample_perSubExample) indicates that items in the outermost collection will be of type typeof(OxFordDefinition_perGroup_perMainExample_perSubExample) . typeof(OxFordDefinition_perGroup_perMainExample_perSubExample)指示最外面的集合中的项目类型为typeof(OxFordDefinition_perGroup_perMainExample_perSubExample) However, in fact the items in the array or list are of type OxFordDefinition_perGroup_perMainExample_perSubExample[] or List<OxFordDefinition_perGroup_perMainExample_perSubExample> respectively, which cannot, of course, be assigned to this type. 但是,实际上,数组或列表中的项目分别是OxFordDefinition_perGroup_perMainExample_perSubExample[]List<OxFordDefinition_perGroup_perMainExample_perSubExample>类型,它们当然不能分配给该类型。 This XmlSerializer code generation fails. XmlSerializer代码生成失败。

If you remove the type setting entirely from your [XmlArrayItem] attribute then both versions of your type will be serializable to XML: 如果您从[XmlArrayItem]属性中完全删除类型设置,则该类型的两个版本都可以序列化为XML:

[System.Xml.Serialization.XmlArrayItemAttribute("_perSubExample", IsNullable = false)]
public List<List<OxFordDefinition_perGroup_perMainExample_perSubExample>> _perMainExample
{
    get
    {
        return this._perMainExampleField;
    }
    set
    {
        this._perMainExampleField = value;
    }
}

Sample fiddle . 样品提琴

Update 更新资料

You asked, it adds extra layer which should not exists. 您询问, 它添加了不应该存在的额外层。 any idea? 任何想法?

This is because you are using nested lists or jagged arrays. 这是因为您使用的是嵌套列表或锯齿状数组。 Change it to be a simple list or 1-d array: 将其更改为简单列表或一维数组:

private List<OxFordDefinition_perGroup_perMainExample_perSubExample> _perMainExampleField;

/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("_perSubExample", IsNullable = false)]
public List<OxFordDefinition_perGroup_perMainExample_perSubExample> _perMainExample
{
    get
    {
        return this._perMainExampleField;
    }
    set
    {
        this._perMainExampleField = value;
    }
}

Sample fiddle #2 . 样本小提琴2

I then downloaded the entire XML from http://pastebin.com/raw/BJhRfFNf and ran xsd.exe to generate a schema, and then classes, from the XML, and I was able to reproduce your problem - incorrect classes were generated. 然后,我从http://pastebin.com/raw/BJhRfFNf下载了整个XML,并运行xsd.exe生成了一个架构,然后从该XML中生成了类,并且我能够重现您的问题-生成了错误的类。 I then manually changed the jagged array to a flat array (a List<T> would work fine also) and was able to serialize and deserialize the XML without an exception getting thrown: 然后,我手动将锯齿状的数组更改为平面数组( List<T>也可以正常工作),并且能够对XML进行序列化和反序列化,而不会引发异常:

Sample fiddle #3 . 样本小提琴#3

Unfortunately, it appears that only the first </_perMainExample> node is successfully deserialized using these tweaked classes, so at this point this auto-generated code just doesn't seem viable. 不幸的是,使用这些经过调整的类,似乎只有第一个 </_perMainExample>节点已成功反序列化,因此,此时此自动生成的代码似乎并不可行。

I'm not sure why xsd.exe generated bad code here, you might want to ask another question or open an issue with Microsoft. 我不确定为什么xsd.exe在这里生成了错误的代码,您可能想问另一个问题或与Microsoft打开问题。

Final Update 最终更新

It looks as though xsd.exe (and thus Paste XML as Classes ) is having trouble with a repeating element that contains nested repeating elements: 看起来xsd.exe (因此将XML粘贴xsd.exe )在包含嵌套的重复元素的重复元素方面遇到了麻烦:

<_perMainExample>
  <_perSubExample>
  </_perSubExample>

  <_perSubExample>
  </_perSubExample>
</_perMainExample>

<_perMainExample>
  <_perSubExample>
  </_perSubExample>

  <_perSubExample>
  </_perSubExample>
</_perMainExample>

I'm not sure what the problem is, but at this point I recommend switching to a different code-generation tool such as https://xmltocsharp.azurewebsites.net/ , which generates the following classes: 我不确定是什么问题,但是在这一点上,我建议切换到其他代码生成工具,例如https://xmltocsharp.azurewebsites.net/ ,它会生成以下类:

[XmlRoot(ElementName="_Example")]
public class _Example {
    [XmlElement(ElementName="_SenseNot")]
    public string _SenseNot { get; set; }
    [XmlElement(ElementName="_GrammaticNot")]
    public string _GrammaticNot { get; set; }
    [XmlElement(ElementName="_Desc")]
    public string _Desc { get; set; }
}

[XmlRoot(ElementName="_perSubExample")]
public class _perSubExample {
    [XmlElement(ElementName="_UpperTitle")]
    public string _UpperTitle { get; set; }
    [XmlElement(ElementName="_FormGroup")]
    public string _FormGroup { get; set; }
    [XmlElement(ElementName="_SenseNot")]
    public string _SenseNot { get; set; }
    [XmlElement(ElementName="_GrammaticNot")]
    public string _GrammaticNot { get; set; }
    [XmlElement(ElementName="_Desc")]
    public string _Desc { get; set; }
    [XmlElement(ElementName="_Example")]
    public List<_Example> _Example { get; set; }
    [XmlElement(ElementName="_Synonyms")]
    public string _Synonyms { get; set; }
}

[XmlRoot(ElementName="_perMainExample")]
public class _perMainExample {
    [XmlElement(ElementName="_perSubExample")]
    public List<_perSubExample> _perSubExample { get; set; }
}

[XmlRoot(ElementName="_perGroup")]
public class _perGroup {
    [XmlElement(ElementName="_GroupDesc")]
    public string _GroupDesc { get; set; }
    [XmlElement(ElementName="_GroupSense")]
    public string _GroupSense { get; set; }
    [XmlElement(ElementName="_GroupGrammer")]
    public string _GroupGrammer { get; set; }
    [XmlElement(ElementName="_perMainExample")]
    public List<_perMainExample> _perMainExample { get; set; }
}

[XmlRoot(ElementName="OxFordDefinition")]
public class OxFordDefinition {
    [XmlElement(ElementName="sourceURL")]
    public string SourceURL { get; set; }
    [XmlElement(ElementName="originDesc")]
    public string OriginDesc { get; set; }
    [XmlElement(ElementName="_perGroup")]
    public List<_perGroup> _perGroup { get; set; }
}

Notice that: 注意:

  1. The code generated is much, much cleaner. 生成的代码要干净得多。

  2. An extra level of class _perMainExample is added to encapsulate the inner _perSubExample list. 添加了一个附加级别的_perMainExample类,以封装内部_perSubExample列表。

Sample fiddle #4 which shows that the original and re-serialized XML are identical by calling XNode.DeepEquals() . 样本小提琴#4通过调用XNode.DeepEquals()表明原始XML和重新序列化的XML是相同的。

protobuf 和列表<object> - 如何序列化/反序列化?<div id="text_translate"><p> 我有一个List&lt;object&gt; ,其中包含不同类型的对象,例如整数、字符串和自定义类型。 所有自定义类型都经过 protobuf 调整。 我现在想做的是用 protobuf.net 序列化/反序列化这个列表。 到目前为止,我怀疑我必须显式声明每种类型,不幸的是,这些混合列表构造不可能做到这一点。 因为二进制格式化程序在做这些事情时没有问题,我希望我错过了一些东西,你可以帮助我。 所以我的问题是如何处理 protobuf.net 中的对象。</p></div></object> - protobuf and List<object> - how to serialize / deserialize?

暂无
暂无

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

相关问题 如何序列化List <object> - How to serialize List<object> 如何序列化列表列表 - How to serialize a list of list 如何序列化动态对象的列表属性 - How to serialize list property of a dynamic object protobuf 和列表<object> - 如何序列化/反序列化?<div id="text_translate"><p> 我有一个List&lt;object&gt; ,其中包含不同类型的对象,例如整数、字符串和自定义类型。 所有自定义类型都经过 protobuf 调整。 我现在想做的是用 protobuf.net 序列化/反序列化这个列表。 到目前为止,我怀疑我必须显式声明每种类型,不幸的是,这些混合列表构造不可能做到这一点。 因为二进制格式化程序在做这些事情时没有问题,我希望我错过了一些东西,你可以帮助我。 所以我的问题是如何处理 protobuf.net 中的对象。</p></div></object> - protobuf and List<object> - how to serialize / deserialize? 如何序列化对象以生成子列表? - How to serialize an object to generate a list of childs? 指定如何将对象序列化,如果它在列表中 - Specify how to Serialize my object if it is in a list 如何使用自定义对象的类型序列化列表列表? - How to serialize a list of lists with the type of custom object? 如何序列化/反序列化List <class object> 与protobuf? - how to serialize / deserialize List<class object> with protobuf? 如何序列化自定义对象类型的列表 - How to serialize a List of custom object types 如何序列化列表 <object> 有专用于JSON的名称? - How to serialize List<object> with dedicated name to JSON?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM