Explicit JSON serialization with DataContractJsonSerializer

If you somehow need to serialize a CLR object to JSON in your Microsoft .Net project, you can use the DataContractJsonSerializer. For this snippet you need to reference System.Runtime.Serialization and System.Servicemodel.Web.

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace ConsoleExplicitJson
{
    class Program
    {
        static void Main(string[] args)
        {
            Garage garage = new Garage();

            garage.Cars.Add(new Car
            {
                Name = "Saab",
                Color = "Red",
                PurchaseDate = new DateTime(1975, 4, 12)
            });
            garage.Cars.Add(new Car
            {
                Name = "Opel",
                Color = "Blue",
                PurchaseDate = new DateTime(1988, 9, 4)
            });
            garage.Cars.Add(new Car
            {
                Name = "Fiat",
                Color = "Silver metalic",
                PurchaseDate = new DateTime(1999, 2, 21)
            });
            garage.Opened = true;

            DataContractJsonSerializer jsonSerializer =
                new DataContractJsonSerializer(typeof(Garage));

            MemoryStream memoryStream = new MemoryStream();
            jsonSerializer.WriteObject(memoryStream, garage);
            memoryStream.Flush();
            memoryStream.Position = 0;
            StreamReader streamReader = new StreamReader(memoryStream);

            string jsonGarage = streamReader.ReadToEnd();

            // Returns the object in JSON:
            //
            //	{"Cars":
            //		[
            //			{"Color":"Red","Name":"Saab",
            //				"PurchaseDate":"\/Date(166485600000+0200)\/"},
            //			{"Color":"Blue","Name":"Opel",
            //				"PurchaseDate":"\/Date(589327200000+0200)\/"},
            //			{"Color":"Silver metalic","Name":"Fiat",
            //				"PurchaseDate":"\/Date(919551600000+0100)\/"}
            //		],
            //	"Opened":true}

        }
    }

    [DataContract]
    class Car
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public string Color { get; set; }
        [DataMember]
        public DateTime PurchaseDate { get; set; }
    }

    [DataContract]
    class Garage
    {
        public Garage()
        {
            Cars = new List<Car>();
        }

        [DataMember]
        public List<Car> Cars { get; set; }
        [DataMember]
        public bool Opened { get; set; }
    }
}  More...