小梦本例主要实现以下四点内容:
[task]public class Car
{
public int Id { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
}[/task]
[task]private List<Car> buildObjectGraph()
{
var myCars = new List<Car>();
myCars.Add(new Car() { Id = 1, Make = "Oldsmobile", Model = "Cutlas Supreme", Year = 1985 });
myCars.Add(new Car() { Id = 2, Make = "Geo", Model = "Prism", Year = 1993 });
myCars.Add(new Car() { Id = 3, Make = "Ford", Model = "Escape", Year = 2005 });
return myCars;
}[/task]
[task]
private async Task writeXMLAsync()
{
var myCars = buildObjectGraph();
var serializer = new DataContractSerializer(typeof(List<Car>));
using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(
XMLFILENAME,
CreationCollisionOption.ReplaceExisting))
{
serializer.WriteObject(stream, myCars);
}
resultTextBlock.Text = "Write succeeded";
}
[/task]
[task]
private async Task readJsonAsync()
{
// Notice that the write **IS** identical ... except for the serializer.
string content = String.Empty;
var myStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(JSONFILENAME);
using (StreamReader reader = new StreamReader(myStream))
{
content = await reader.ReadToEndAsync();
}
resultTextBlock.Text = content;
}
[/task]
[task]private async Task deserializeXmlAsync()
{
string content = String.Empty;
List<Car> myCars;
var xmlSerializer = new DataContractSerializer(typeof(List<Car>));
var myStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(XMLFILENAME);
myCars = (List<Car>)xmlSerializer.ReadObject(myStream);
foreach (var car in myCars)
{
content += String.Format("ID: {0}, Make: {1}, Model: {2} ", car.Id, car.Make, car.Model);
}
resultTextBlock.Text = content;
}[/task]
[task]private async Task deserializeJsonAsync()
{
string content = String.Empty;
List<Car> myCars;
var jsonSerializer = new DataContractJsonSerializer(typeof(List<Car>));
var myStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(JSONFILENAME);
myCars = (List<Car>)jsonSerializer.ReadObject(myStream);
foreach (var car in myCars)
{
content += String.Format("ID: {0}, Make: {1}, Model: {2} ", car.Id, car.Make, car.Model);
}
resultTextBlock.Text = content;
}[/task]
欢迎光临编程小梦。