Serializing an Object to JSON

To serialize an object to JSON you will need  to create a data contract, which is a class containing all the properties marked with attributes. To demonstrate this I will create a Person class and apply a DataContractAttribute and DataMemberAttribute.

[DataContract]
internal class Person
{
	[DataMember]
	internal string name;

	[DataMember]
	internal int age;
}

Now we need to write some code to populate the Person class with some data and then use DataContractJsonSerializer to serialize the object to Json and just for you information DataContractJsonSerializer has been available since .NET Framework 3.5.

Instantiate DataContractJsonSerializer and pass the Person type to the constructor, then use the WriteObject method to write the Person object to a stream and then use a StreamReader to read the stream and see the serialized result.

// Create a Person object and define valuues
Person p = new Person();
p.name = "John";
p.age = 42;

// Create a memory stream.
MemoryStream stream = new MemoryStream();

// Serialize object of type Person.
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));

// Write object to stream.
serializer.WriteObject(stream, p);

// Position stream to 0.
stream.Position = 0;

// Create a stream reader.
StreamReader streamReader = new StreamReader(stream);

// Output JSON data to console.
Console.WriteLine (streamReader.ReadToEnd());

Deserialize JSON to a Class.

To deserialize Json I will create a text file called Person.json containing the correct formatting:

{
	"age":42,
	"name":"John"
}

I am going to use a FileStream to read the file and then use the DataContractJsonSerializer again, but this time instead of calling the WriteObject method, we are going to use the ReadObject by passing the stream and  then assign the returned value to a Person object by casting it as a Person type.

// Create a stream to read JSON content from a text file.
FileStream stream = new FileStream("Person.json", FileMode.Open);

// Serialize object of type Person.
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));

// Position stream to 0.
stream.Position = 0;

// Deserialize JSON data from stream
Person p = (Person)serializer.ReadObject(stream);

// Output deserialized JSON data to console.
Console.WriteLine("Deserialize results:");
Console.WriteLine("name = {0}", p.name);
Console.WriteLine("age = {0}", p.age);

I hope this is informative if you are planning to work with JSON and .NET in the near future. I have the full source code in GitHub if you wish to download it, compile it and play with it on your own machine:

GitHub: json-serialization-example

 

 

Shares