Serialization to and from JSON document text using DataContractJsonSerializer object

Description and code samples
Table of Contents
Description

In order to serialize an object to JSON using the DataContractJSonSerializer object the following is required:

  1. The “DataMember” attribute is used to mark the properties to serialize (private or public).
  2. With this attribute is possible to set the output name of each property, if it is required, if the default value should be used and set the output order of each property;
  3. The “DataContract” attribute is used to classify the class as serializable;
  4. For each properties of complex types the “KnownType” attribute must be used, one per each complex type. Alternatively, a list of know types can be enumerated in the Serialize method.
Operations
Serialize/De-serialize to/from JSON string/object using MemoryStream
How to do it
public string Serialize<T>(T obj, string encoding) where T:class
{
	string json = string.Empty;

	DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
	using (MemoryStream ms = new MemoryStream())
	{
		using (var jsonw = JsonReaderWriterFactory.CreateJsonWriter(ms,Encoding.GetEncoding(encoding)))
		{
			serializer.WriteObject(jsonw, obj);
			jsonw.Flush();
			json = Encoding.GetEncoding(encoding).GetString(ms.ToArray());
		}
	}

	return json;
}

public T Deserialize<T>(string json, string encoding) where T:class
{
	T obj = Activator.CreateInstance<T>();

	using (MemoryStream ms = new MemoryStream(Encoding.GetEncoding(encoding).GetBytes(json)))
	{
		using (XmlDictionaryReader jsonr = JsonReaderWriterFactory.CreateJsonReader(ms, Encoding.GetEncoding(encoding), XmlDictionaryReaderQuotas.Max, null))
		{
			DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
			obj = (T)serializer.ReadObject(jsonr);
		}
	}

	return obj;
}
How to use it
// Class definition:

[DataContract(Name = "Book", Namespace="www.training.com")]
public class Book
{
    [DataMember(EmitDefaultValue=true,IsRequired=true,Name="Author",Order=1)]
    public string Author { get; set; }

    [DataMember(EmitDefaultValue = true, IsRequired = true, Name = "Title", Order = 2)]
    public string Title { get; set; }

}

[DataContract(Name = "Library", Namespace = "www.training.com")]
public class Library
{
    public  Library()
    {
    }

    [DataMember(EmitDefaultValue = false, IsRequired = true, Name = "Books", Order = 2)]
    public List<Book> Books;

    [DataMember(EmitDefaultValue = false, IsRequired = true, Name = "LibName", Order = 1)]
    public string Name { get; set; }
}
// Code to serialize/de-serialize object:

List<Book> lvBooks = new List<Book>();

Book lvBook = new Book();
lvBook.Author = "João Seixas";
lvBook.Title = "Training serialization book";
lvBooks.Add(lvBook);

lvBook = new Book();
lvBook.Author = "João Seixas";
lvBook.Title = "Training serialization book (Second edition)";
lvBooks.Add(lvBook);

Library lvLibrary = new Library { Name = "MyLibrary", Books = lvBooks };

// SERIALIZING TO JSON 

string json = Serialize(lvLibrary, "utf-8");

// DE-SERIALIZING FROM JSON 

lvLibrary = Deserialize<Library>(json,"utf-8");
JSON text:

{"LibName":"MyLibrary","Books":[{"Author":"João Seixas","Title":"Training serialization book"},{"Author":"João Seixas","Title":"Training serialization book (Second edition)"}]}