While working on one of my favorites eMagid projects – rentalengine, one of our technicians had to deal with a small hurdle – How to convert custom object into JSON, so it can be consumed by our rich JavaScript UI.
The solution is actually way more simple than you’d imagine – There is a built it serializer just for that in the System.Web.Script.Serialization namespace.
So… let’s see it in action :
First – let’s built our object:
[Serializable()]
public class MyObject {
public string StringField { get; set; }
public int[] Numbers { get; set; }
public String[] Names { get; set; }
}
Now the fun part – Convert to JSON
Step 1. Import the namespace
using System.Web.Script.Serialization;
Step 2. Let’s JSON it!
JavaScriptSerializer o = new JavaScriptSerializer(); string json = o.Serialize(Images);
Is that all???
YES! that’s all. You just converted your object (custom, ADO, Linq object, or otherwise) to JSON!!