- Course
- Data serialization
- JavaScriptSerializer: Serialize objects
JavaScriptSerializer: Serialize objects
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a C# program that serialize and deserialize objects in JSON format. To do this, you can use the JavaScriptSerializer
class included in the System.Web.Extensions
namespace.
First implement a Person class with three properties (Name, Age and City). The City class will have two properties (Name and Population). Then create a person object and use the serializer of the JavaScriptSerializer
object to save the data in file.json, later deserialize the file.json and print it on the screen. Remember to prepare a ToString()
method to print the Person class.
Input
Output
Solution
using System;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
public class JSONJavaScriptSerializer
{
static string nameFile = "out.json";
public static void Main(string[] args)
{
Person person = new Person()
{
Name = "Nauj",
Age = 26,
City = new City()
{
Name = "Spain",
Population = 13456766
}
};
Serialize(person);
person = Deserialize();
Console.WriteLine(person.ToString());
Console.ReadLine();
}
public static void Serialize(Person p)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonData = js.Serialize(p);
File.WriteAllText(nameFile, jsonData);
}
public static Person Deserialize()
{
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonData = File.ReadAllText(nameFile);
Person person = js.Deserialize<Person>(jsonData);
return person;
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public City City { get; set; }
public override string ToString()
{
StringBuilder str = new StringBuilder();
str.AppendLine("Name: " + Name);
str.AppendLine("Age: " + Age);
str.AppendLine("City: " + City.Name);
return str.ToString();
}
}
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
}