How to serialize and deserialize Json objects in C#

A simple console app to demonstrate this.

After creating your Visual Studio application, console or otherwise, make sure the System.Web.Extension reference is added:

Suppose we have an object we wish to serialize/deserialize, such as an instance of this class:

public class Shared
{
   public List<string> Emails { get; set; }
   public string Message { get; set; }
   public List<string> Ids { get; set; }
}

One possible way is to make use of the JavaScriptSerializer class.

By the way, here is a useful StackOverflow link if you are having trouble finding JavaScriptSerializer in .NET 4.0:

https://stackoverflow.com/questions/7000811/cannot-find-javascriptserializer-in-net-4-0

So that in this example, we not only instantiate our example class for serialization using JavaScriptSerializer, but deserialize it back into the original object as well:

Console application code listing as follows:

Program.cs

using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace Json
{
   public class Shared
   {
      public List<string> Emails { get; set; }
      public string Message { get; set; }
      public List<string> Ids { get; set; }
   }

   class Program
   {
      static void Main(string[] args)
      {
         var emails = new List<string> { "andrew.webb@gmail.com", "greg.proops@hotmail.com" };
         var ids = new List<string> { "1234", "3456", "6789" };
         var shared = new Shared { Emails = emails, Message = "Just testing", Ids = ids };

         var serializer = new JavaScriptSerializer();
         var str = serializer.Serialize(shared);
        
         var deserialize = serializer.Deserialize<Shared>(str);
      }
   }
}

On debugging and inspecting the text outputs, see that the object is serialized as follows, by inspecting the string returned by the serializer in the text viewer.

This is by inspecting the value returned by the following line during debugging:

var str = serializer.Serialize(shared);

And on deserialization, by stepping through the last line of the code, see that an instance of the original Shared object is returned, as shown: