public static void SerializeJsonDataContract(int houseNo = 0, string street = null, string desc = null) { Address ad = new Address { HouseNo = houseNo, Street = street, Desc = desc }; DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Address)); using (FileStream fs = File.Open(@"c:\TestOutput\testJsonDataContractSerializer.js", FileMode.OpenOrCreate, FileAccess.ReadWrite)) { ser.WriteObject(fs, ad); } //to json stream DataContractJsonSerializer using (MemoryStream ms = new MemoryStream()) using (StreamReader sr = new StreamReader(ms)) { ser.WriteObject(ms, ad); ms.Position = 0; Console.WriteLine(sr.ReadToEnd()); } //deserialize DataContractJsonSerializer using (FileStream fs = File.OpenRead(@"c:\TestOutput\testJsonDataContractSerializer.js")) { Address address = (Address)ser.ReadObject(fs); } Console.WriteLine("Finished SerializeJsonDataContract"); }
public static void SerializeXmlDataContract(int houseNo = 0, string street = null, string desc = null) { Address ad = new Address { HouseNo = houseNo, Street = street, Desc = desc }; DataContractSerializer ds = new DataContractSerializer(typeof(Address)); using (XmlWriter xw = XmlWriter.Create(@"C:\TestOutput\testXmlDataContract.xml")) { ds.WriteObject(xw, ad); } Console.WriteLine("Finished SerializeXmlDataContract"); }
public static void SerializeJsonJavaScriptSerializer(int houseNo = 0, string street = null, string desc = null) { Address ad = new Address { HouseNo = houseNo, Street = street, Desc = desc }; JavaScriptSerializer js = new JavaScriptSerializer(); // serialize back to file JavaScriptSerializerS using (StreamWriter sw = new StreamWriter(@"c:\TestOutput\testJavaScriptSerializer.js")) { string temp = js.Serialize(ad); sw.Write(temp); } using (StreamReader fs = new StreamReader(@"c:\TestOutput\testJavaScriptSerializer.js")) { ad = js.Deserialize<Address>(fs.ReadToEnd()); } Console.WriteLine("Finished SerializeJsonJavaScriptSerializer"); }
public static void SerializeXmlSerializer(int houseNo = 0, string street = null, string desc = null) { Address ad = new Address { HouseNo = houseNo, Street = street, Desc = desc }; XmlSerializer xs = new XmlSerializer(typeof(Address)); using (XmlWriter xw = XmlWriter.Create(@"C:\TestOutput\testXmlSerialize.xml")) { xs.Serialize(xw, ad); } //aand deserialize back and display //using(FileStream fs = File.OpenRead(@"C:\TestOutput\testXmlSerialize.xml")) using (StreamReader sr = new StreamReader(@"C:\TestOutput\testXmlSerialize.xml")) { Console.WriteLine(sr.ReadToEnd()); } Console.WriteLine("Finished SerializeXmlSerializer"); }