windows phone8.1:Xml,Json序列化和反序列化

时间:2023-01-16 14:59:24

原文:windows phone8.1:Xml,Json序列化和反序列化

小梦本例主要实现以下四点内容:

  1. 将Car对象序列化为xml
  2. 将Car对象序列化为Json
  3. 将xml反序列化为Car对象
  4. 将json反序列化为json对象

Car类如下:

[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]

实例化Car对象:

[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]

将Car对象序列化为xml:

[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]

将Car对象序列化为Json:

[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]

将xml反序列化为Car对象:

[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]

将json反序列化为json对象

[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]

欢迎光临编程小梦。