C#XML反序列化数组元素null

时间:2012-05-03 08:49:27

标签: c# xml deserialization xmlserializer

我正在尝试从REST API反序列化响应。

"<FieldListDTO xmlns=\"api.playcento.com/1.0\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
<Allfield>
<FieldDTO>
<Fieldname>Mobile nr</Fieldname>
<Fieldtype>T</Fieldtype>
<Fieldvalue>003241234578</Fieldvalue>
<Fk_id_page>CP584ea74ce5ad4e2d8561d75fc6944f96</Fk_id_page>
<Id_field>FI152dcde5ef9849898b12d6a3f2cdb4ee</Id_field>
<Required>true</Required>
</FieldDTO>
</Allfield>
<Totalcount>1</Totalcount>
</FieldListDTO>"

Field类:

namespace PlaycentoAPI.Model
{
    [XmlRoot("FieldListDTO",Namespace = "api.playcento.com/1.0")]
    [XmlType("FieldListDTO")]
    public class FieldListDTO
    {
        public FieldListDTO() { }

        [XmlElement("Totalcount")]
        public int TotalCount { get; set; }

        [XmlArray("Allfield")]
        [XmlArrayItem("FieldDTO", typeof(Field))]
        public Field[] Field { get; set; }

    }
    [XmlRoot("FieldDTO", Namespace = "api.paycento.com/1.0")]
    [XmlType("FieldDTO")]
    public class Field
    {
        public Field()
        {
        }

        [XmlElement("Id_field")]
        public string ID_Field { get; set; }
        [XmlElement("Fieldtype")]
        public string FieldType { get; set; }
        [XmlElement("Fk_id_page")]
        public string FK_ID_PAGE { get; set; }
        [XmlElement("Required")]
        public bool Required { get; set; }
        [XmlElement("Fieldname")]
        public string FieldName { get; set; }
        [XmlElement("Fieldvalue")]
        public string FieldValue { get; set; }
    }
}

我的代码调用API并反序列化它:

string response = Helper.PerformAndReadHttpRequest(uri, "GET", "");
                FieldListDTO myObject;
                XmlReaderSettings settings = new XmlReaderSettings();
                using (StringReader textReader = new StringReader(response))
                {
                    using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
                    {
                        XmlSerializer mySerializer = new XmlSerializer(typeof(FieldListDTO));
                        myObject = (FieldListDTO)mySerializer.Deserialize(xmlReader);
                    }
                }
                return myObject.Field;

在我的实际回答中,我回来了14场FieldDTO。反序列化xml后,FieldListDTO myObject包含TotalCount = 14,Field是一个包含14个Field的数组。但是这些字段的所有属性都是NULL(或false)。

我正在为其他几个API调用使用相同的方法。我比较了类,我看到的唯一区别是类(Field)有bool属性。所以我认为这就是问题所在。我已将bool属性更改为字符串,但在反序列化后仍然所有属性都为NULL。

1 个答案:

答案 0 :(得分:1)

首先要注意的是FieldDTO类中的命名空间与XML文档中的命名空间不匹配。

"api.paycento.com/1.0"
"api.playcento.com/1.0"