- Course
- Data serialization
- DataContractJsonSerializer: Serialize objects
DataContractJsonSerializer: 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 DataContractJsonSerializer
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 DataContractJsonSerializer
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.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
public class JSONDataContractJsonSerializer
{
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());
}
public static void Serialize(Person p)
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Person));
using (MemoryStream msObj = new MemoryStream())
{
js.WriteObject(msObj, p);
msObj.Position = 0;
using (StreamReader sr = new StreamReader(msObj))
{
string jsonData = sr.ReadToEnd();
File.WriteAllText(nameFile, jsonData);
}
}
}
public static Person Deserialize()
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Person));
Person person;
string jsonData = File.ReadAllText(nameFile);
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonData)))
{
person = (Person)js.ReadObject(ms);
}
return person;
}
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
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();
}
}
[DataContract]
public class City
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Population { get; set; }
}
}