110,534
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.Text;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
Customer person = new Customer();
person.Name = "John Jones";
person.Entered = new DateTime(2007, 10, 10);
person.Addresses.Add(new Address());
person.Addresses.Add(new Address());
TestJson(person);
TestIFormatter(person);
Console.ReadLine();
}
private static void TestIFormatter(Customer person)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("testIFormatter", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, person);
stream.Close();
IFormatter formatter2 = new BinaryFormatter();
Stream stream2 = new FileStream("testIFormatter", FileMode.Open, FileAccess.Read, FileShare.Read);
Customer person2 = formatter2.Deserialize(stream2) as Customer;
Console.WriteLine(person2.Name);
}
private static void TestJson(Customer person)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof (Customer));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, person);
string json = Encoding.Default.GetString(ms.ToArray());
ms.Close();
Console.WriteLine(json);
// *** Start from scratch with deserialization
//ms = new FileStream(Server.MapPath("jsonoutput.txt"), FileMode.Open);
ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
ser = new DataContractJsonSerializer(typeof (Customer));
Customer person2 = ser.ReadObject(ms) as Customer;
ms.Close();
Console.WriteLine(person2.Name);
}
#region Nested type: Address
[Serializable]
public class Address
{
public string City = "Paia";
public string State = "HI";
public string Street = "32 Kaiea Place";
public string Zip = "96779";
}
#endregion
#region Nested type: Customer
[Serializable]
public class Customer
{
public List<Address> Addresses = new List<Address>();
public DateTime Entered = DateTime.Now;
public string Name = "John";
}
#endregion
}
}