序列化和反序列化 Windows Phone 8 应用程序中的对象列表 [英] Serializing and deserializing a list of objects in a Windows Phone 8 app
问题描述
给定一些对象列表:
List<Car> carlist = new List<Car>();
如何将此列表序列化为 XML 或二进制文件并将其反序列化?
How can I serialize this list as an XML or binary file and deserialize it back?
到目前为止我有这个,但它不起作用.
I have this so far but it doesn't work.
//IsolatedStorageFile isFile = IsolatedStorageFile.GetUserStoreForApplication();
//IsolatedStorageFileStream ifs = new IsolatedStorageFileStream("myxml.xml", FileMode.Create,isFile);
//DataContractSerializer ser = new DataContractSerializer();
//XmlWriter writer = XmlWriter.Create(ifs);
//ser.WriteObject(writer, carlist);
推荐答案
我正在使用这些方法将 XML 文件保存并加载到独立存储中:
I'm using these methods to Save and Load from a XML file in/to the IsolatedStorage :
public static class IsolatedStorageOperations
{
public static async Task Save<T>(this T obj, string file)
{
await Task.Run(() =>
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = null;
try
{
stream = storage.CreateFile(file);
XmlSerializer serializer = new XmlSerializer(typeof (T));
serializer.Serialize(stream, obj);
}
catch (Exception)
{
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
});
}
public static async Task<T> Load<T>(string file)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
T obj = Activator.CreateInstance<T>();
if (storage.FileExists(file))
{
IsolatedStorageFileStream stream = null;
try
{
stream = storage.OpenFile(file, FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof (T));
obj = (T) serializer.Deserialize(stream);
}
catch (Exception)
{
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
return obj;
}
await obj.Save(file);
return obj;
}
}
您可以在 catch() 中自定义错误处理.
You can customize the error handling in the catch().
此外,您可以根据需要调整 Load 方法,在我的情况下,我试图从文件加载,如果不存在,它会创建一个默认的并放置根据提供的类型的默认序列化对象构造函数.
Also, you can adjust the Load method to your needs, in my case I am trying to load from a file and if doesn't exist, it creates a default one and puts the default serialized object of the type provided according to the constructor.
更新:
假设您有汽车列表:
列表<汽车> carlist=新列表<汽车 >();
要保存,您可以将它们称为 await carlist.Save("myXML.xml");
,因为它是一个异步的Task
(async
).
To save, you can just call them as await carlist.Save("myXML.xml");
, as it is an asynchronous Task
(async
).
要加载,var MyCars = await IndependentStorageOperations.Load<列表
(我想,我还没有像这样使用它,到目前为止作为List...
To load, var MyCars = await IsolatedStorageOperations.Load< List< Car> >("myXML.xml").
(I think, I haven't used it like this, as a List so far...
这篇关于序列化和反序列化 Windows Phone 8 应用程序中的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!