Serialization to and from JSON document file using DataContractJSonSerializer object

Description and code samples
Table of Contents
Summary

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 file/object using FileStream
How to do it
 public void SerializeToFile<T>(T obj, string encoding, string path) where T:class
{
	DataContractJsonSerializer serializer = new DataContractJsonSerializer((typeof(T)));
	using (FileStream fs = new FileStream(path, FileMode.Create))
	{
		using (var jsonw = JsonReaderWriterFactory.CreateJsonWriter(fs, Encoding.GetEncoding(encoding)))
		{
			serializer.WriteObject(jsonw, obj);
			jsonw.Flush();
		}
	}
}

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

	DataContractJsonSerializer serializer = new DataContractJsonSerializer((typeof(T)));
	using (FileStream fs = new FileStream(path, FileMode.Open))
	{
		using (XmlDictionaryReader jsonr = JsonReaderWriterFactory.CreateJsonReader(fs, Encoding.GetEncoding(encoding),XmlDictionaryReaderQuotas.Max,null))
		{
			obj = (T) serializer.ReadObject(jsonr) as T;
		}
	}

	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 = SerializetoFIle(lvLibrary, "utf-8", "c:\temp\file.json");

// DE-SERIALIZING FROM JSON 

lvLibrary = DeserializeFromFile<Library>("c:\temp\file.json","utf-8");
JSON file text:

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