Friday, July 24, 2015

Use the JavaScriptSerializer in C# to serialize anonymous types.

This test passes:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Script.Serialization;
namespace Atty.Core.Tests
{
   [TestClass]
   public class SerializationTest
   {
      [TestMethod]
      public void serialization_works()
      {
         var anonymous = new
         {
            Foo = "Bar",
            Baz = 13,
         };
         JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
         string serialization = javaScriptSerializer.Serialize(anonymous);
         Assert.AreEqual(serialization, "{\"Foo\":\"Bar\",\"Baz\":13}");
      }
   }
}

 
 

I had to reference in the System.Web.Extensions assembly to get the System.Web.Script.Serialization using declaration to work. I really only have used the JavaScriptSerializer to deserialize, but I was curious to see what serialization back the other way would look like so here it is.

 
 

Addendum 1/8/2016: System.Web.Extensions may be found at:

  • C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5
  • C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0

No comments:

Post a Comment