Tuesday, April 15, 2014

JavaScriptSerializer is new as of the ASP.NET 4.5 Framework and is a great way to deserialize stringified JSON to a type!

protected void SolarSystemCallBackPanel_Callback(object sender,
      CallbackEventArgsBase e)
{
   string json = e.Parameter;
   JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
   Measurements measurements = javaScriptSerializer.Deserialize<Measurements>(json);
   UpdateEverything(measurements);
}

 
 

In this example, my type that I deserialize to is:

using System;
namespace DummyDevExpressApplication.Models
{
   public class Measurements
   {
      public Int32 Diameter { get; set; }
      public decimal Distance { get; set; }
   }
}

 
 

The stringified JSON I give as an example here would end up putting 13 in the Diameter property and 3.14 in the Distance property.

No comments:

Post a Comment