How To: Serialize and Deserialize JSON with .NET Framework

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. (more…)

How to Convert JSON to a Class in C#

I have been working on .Net projects where I need to work with JSON to a class in C#. I came across a web site created by Jonathan Keith using the popular JSON.Net library by James Newton-King.

The web site allows me to copy and paste JSON code to a form and by pressing the generate button I was able to get back a class that I can copy and use in my .Net project. This web site is very useful to me since I am also using the JSON.Net library in my current project to Deserialise JSON data in to an object.

http://json2csharp.com

json2csharp_web

Shares