What is JSON Serialization?
Converting a .Net object to a JSON object is know as JSON serialization and vice versa is known as JSON deserialization.
Just follow the below code and do the changes as per your requirement.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace XML_Serilization_and_Deserilization
{
class Program
{
static void Main(string[] args)
{
//Serilization
Teacher[] teachers = new Teacher[2]{
new Teacher() { TeacherId=1,Teachername="T1"},
new Teacher() { TeacherId = 2, Teachername = "T2" } };
School obj = new School() { SchoolName = "School1", SchoolAddress = "India", ZipCode = 12344, Teachers = teachers };
DataContractJsonSerializer serObj = new DataContractJsonSerializer(typeof(School));
MemoryStream stream = new MemoryStream();
serObj.WriteObject(stream, obj);
string s1= Encoding.UTF8.GetString(stream.ToArray());
File.WriteAllText(@"D:\Users\aj\Desktop\Test\School.txt",s1);
//Desilization
School DeseriledObj= (School)serObj.ReadObject(new MemoryStream(File.ReadAllBytes(@"D:\Users\aj\Desktop\Test\School.txt")));
}
}
public class School
{
public string SchoolName { get; set; }
public string SchoolAddress { get; set; }
public int ZipCode { get; set; }
public Teacher[] Teachers { get; set; }
}
public class Teacher
{
public int TeacherId { get; set; }
public string Teachername { get; set; }
}
}
No comments:
Post a Comment