问题反序列化对象的列表 [英] Problems deserializing List of objects
本文介绍了问题反序列化对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法反序列化对象的列表。我可以得到的只是一个对象序列化到一个对象,但无法获取列表。我没有得到任何错误,它只是返回一个空列表。这是被返回的XML:
<地点和GT;
<所在地的locationType =建设locationtypeid =1>
< ID> 1 LT; / ID>
<名称>建筑物名称和LT; /名称>
<描述>建筑<的说明; /描述>
< /地点>
< /地点>
这是类我有,我在 GETALL 反序列化code>方法:
[序列化()]
[XmlRoot(位置)]
公共类建筑
{
私人字符串的方法;
[的XmlElement(ID)]
公众诠释LocationID {搞定;组; }
[的XmlElement(名称)]
公共字符串名称{;组; }
[的XmlElement(说明)]
公共字符串描述{搞定;组; }
[的XmlElement(mubuildingid)]
公共字符串MUBuildingID {搞定;组; }
公开名单<建筑> GETALL()
{
变种listBuildings =新的List<建筑GT;();
变种建筑=新楼();
VAR请求= WebRequest.Create(法)为HttpWebRequest的;
VAR响应= request.GetResponse()作为HttpWebResponse;
变种的StreamReader =新的StreamReader(response.GetResponseStream());
TextReader的读者= StreamReader的;
无功序列化=新的XmlSerializer(typeof运算(列表<建筑>),
新XmlRootAttribute(){的ElementName =位置});
listBuildings =(列表<建筑>)serializer.Deserialize(读卡器);
返回listBuildings;
}
}
解决方案
尝试这样的:
[XmlRoot(位置)]
公共类BuildingList
{
公共BuildingList(){项目=新的List<建筑GT;();}
[的XmlElement(位置)]
公开名单<建筑>项目{获得;设置;}
}
然后反序列化整个BuildingList对象。 p>
XmlSerializer的VAR =新的XmlSerializer(typeof运算(BuildingList));
变种名单=(BuildingList)xmlSerializer.Deserialize(XML);
I am having trouble deserializing a list of objects. I can get just one object to serialize into an object but cannot get the list. I get no error it just returns an empty List. This is the XML that gets returned:
<locations>
<location locationtype="building" locationtypeid="1">
<id>1</id>
<name>Building Name</name>
<description>Description of Building</description>
</location>
</locations>
This is the class I have and I am deserializing in the GetAll
method:
[Serializable()]
[XmlRoot("location")]
public class Building
{
private string method;
[XmlElement("id")]
public int LocationID { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("description")]
public string Description { get; set; }
[XmlElement("mubuildingid")]
public string MUBuildingID { get; set; }
public List<Building> GetAll()
{
var listBuildings = new List<Building>();
var building = new Building();
var request = WebRequest.Create(method) as HttpWebRequest;
var response = request.GetResponse() as HttpWebResponse;
var streamReader = new StreamReader(response.GetResponseStream());
TextReader reader = streamReader;
var serializer = new XmlSerializer(typeof(List<Building>),
new XmlRootAttribute() { ElementName = "locations" });
listBuildings = (List<Building>)serializer.Deserialize(reader);
return listBuildings;
}
}
解决方案
Try this:
[XmlRoot("locations")]
public class BuildingList
{
public BuildingList() {Items = new List<Building>();}
[XmlElement("location")]
public List<Building> Items {get;set;}
}
Then deserialize the whole BuildingList object.
var xmlSerializer = new XmlSerializer(typeof(BuildingList));
var list = (BuildingList)xmlSerializer.Deserialize(xml);
这篇关于问题反序列化对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文