Monday, July 14, 2014

serialize object to JSON format in ASP.NET

1) public static Company GetData()
{
    return new Company()
    {
        Title = "Company Ltd",
        Employees = new List<Employee>()
            {
                new Employee(){ Name = "Mark CEO", EmployeeType = EmployeeType.CEO },
                new Employee(){ Name = "Matija Božičević", EmployeeType = EmployeeType.Developer },
                new Employee(){ Name = "Steve Developer", EmployeeType = EmployeeType.Developer}
            }
    };
}


JavaScriptSerializer().Serialize

// Load object with some sample data
Company company = GetData();
 
// Pass "company" object for conversion object to JSON string
string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(company);
 
// Write that JSON to txt file
File.WriteAllText(Environment.CurrentDirectory + @"\JSON.txt", json);


The content of that "JSON.txt" file is following:

{"Title":"Company Ltd","Employees":[{"Name":"Mark CEO","EmployeeType":0},{"Name":"Matija
Božičević","EmployeeType":1},{"Name":"Steve Developer","EmployeeType":1}]}


JavaScriptSerializer().Deserialize


string json = File.ReadAllText(Environment.CurrentDirectory + @"\JSON.txt");
             
Company company = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Company>(json);
  
  

No comments:

Post a Comment