【发布时间】:2015-09-07 20:21:55
【问题描述】:
我正在使用 API 来获取有关 Web 应用程序的一些信息。我编写了类来反序列化 XML 响应并添加了 XMLRoot、XMLElement 属性。对于带有子项集合的 XML 响应,我可以使用属性进行反序列化。例如
<?xml version="1.0" encoding="UTF-8"?>
<time-entries>
<time-entry>
//Other sub nodes
</time-entry>
<time-entry>
//Other sub nodes
</time-entry>
</time-entries>
对于像上面这样的 XML 响应,我编写了一个 TimeEntry 类,其中包含时间入口节点的其他属性的属性。然后我用下面的 TimeEntry 类集合编写了另一个类
[XmlRoot("time-entries")]
public class TimeEntryResponse
{
public TimeEntryResponse()
{
}
[XmlElement("time-entry")]
public List<TimeEntry> TimeEntries { get; set; }
}
因此,使用 TimeEntryResponse 类,我可以反序列化 XML 响应,例如问题的顶部。
但我不能像下面的响应那样反序列化。
<?xml version="1.0" encoding="UTF-8"?>
<time-totals>
<total-mins-sum type="integer">382743</total-mins-sum>
<non-billed-mins-sum type="integer">328988</non-billed-mins-sum>
<non-billable-hours-sum type="integer">3137.30</non-billable-hours-sum>
</time-totals>
我还为此响应编写了 TimeTotal 类。
[XmlRoot("time-totals")]
public class TimeTotal
{
[XmlElement("total-mins-sum")]
public double TotalMinsSum { get; set; }
[XmlElement("non-billed-mins-sum")]
public double NonBilledMinsSum { get; set; }
[XmlElement("non-billable-hours-sum")]
public double NonBillableHoursSum { get; set; }
}
然后我写了一个响应类。
public class TimeTotalsResponse : IEntityResponse
{
public TimeTotalsResponse()
{
}
public TimeTotal TimeTotal { get; set; }
}
如您所见,没有此响应的集合,我不知道应该添加响应类 TimeTotal 的哪些属性。
也许我可以将 TimeTotal 类的属性直接放入 TimeTotalResponse 类。但我将使用这个类来反序列化包含 time-totals 节点的类。
【问题讨论】:
-
为什么不直接反序列化到
TimeTotal类?它应该可以工作。或者如果你还需要实现IEntityResponse有TimeTotalsResponse子类TimeTotal而不是封装它。 -
@dbc 我不想序列化 TimeTotal 类。我需要返回一个从 IEntityResponse 派生的类,因为我在这个接口上使用泛型方法做了很多工作。如果你在评论中有不同的意思,你能用代码告诉它吗?
标签: c# xml serialization