【问题标题】:Always empty when using Deserialize on XmlSerializer在 XmlSerializer 上使用反序列化时始终为空
【发布时间】:2012-06-20 15:25:51
【问题描述】:

我想反序列化一些如下所示的 XML:

XML:

     <bookings>
        <booking>
           <timeStart>2012/7/2 11:00:00</timeStart>
           <timeEnd>2012/7/2 12:00:00</timeEnd>
        </booking>
        <booking>
            <timeStart>2012/7/10 08:30:00</timeStart>
            <timeEnd>2012/7/10 10:30:00</timeEnd>
        </booking>         
     </bookings>

我的代码:

       var calUrlStr = "http://xxx.com?action=xxxxxx?x=1&y=2";

       HttpWebRequest webRequest = GetWebRequest(calUrlStr);
       HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

       XmlRootAttribute xRoot = new XmlRootAttribute();
       xRoot.ElementName = "bookings";
       xRoot.IsNullable = true;

       XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyDomain.GCalBooking.GCalBookings), xRoot);

       Stream theStream = response.GetResponseStream();
       StreamReader reader = new StreamReader(theStream);

       MyDomain.GCalBooking.GCalBookings rateResponse = (MyDomain.GCalBooking.GCalBookings)xmlSerializer.Deserialize(reader);

我的班级:

namespace MyDomain.GCalBooking
{
    public class GCalBookings
    {

        public virtual List<Booking> Bookings { get; set; }


    }

    public class Booking
    {

        public string timeStart { get; set; }
        public string timeEnd { get; set; }

    }
}

【问题讨论】:

    标签: c# asp.net .net deserialization


    【解决方案1】:

    XmlElementAttribtue 添加到您的班级:

    public class GCalBookings
    {
        [XmlElement("booking")]
        public virtual List<Booking> Bookings { get; set; }
    }
    

    旁注:为了帮助调试此类内容,请尝试填充您的类,对其进行序列化,然后查看 XML 的结构是什么样的。然后你可以调整你的类,直到生成的 XML 看起来像你想要反序列化的那样。

    【讨论】:

      【解决方案2】:

      问题是,反序列化器不使用 list 属性的 SET 方法,而是通过 GET 方法,然后为每个项目调用 ADD。这意味着,属性 Bookings 必须通过 ctor 初始化。

      c# System.Xml.Serialization does not goes throught set method of Public List<T>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-23
        • 2018-06-14
        • 1970-01-01
        相关资源
        最近更新 更多