To and FromJson Extension Methods
In his recent blog post, Scott Guthrie provided us with an excellent example of converting objects To JSON using Extension Methods. One thing that was missing, however, was how to convert FROM Json back to Objects and deserialize them. Thankfully, that requires the same number of codes and a bit of work with generics.
Here’s Scott’s original code for reference (I changed the casing a bit…):
public static class Json
public static string ToJson (this object obj)
public static string ToJson (this object obj, int recursionDepth)
serializer.RecursionLimit = recursionDepth;
To that, I added one more method (skipping the recusion depth example for brevity):
public static T FromJson<T> (this object obj)
return serializer.Deserialize<T>(obj as string);
With this code, the consumer can pass a Type of object along with the string/stream/etc. and rebuild the objects.
Here’s how to use it. In this example, we’ll use an object from our libraries that goes out and populates “School” objects with their demographic information.
List<School> sch = School.GetSchool();
string jsonString = sch.ToJson();
string jsonSnippet = jsonString.Substring(0, 200); // Trim the results
Our School objects are contained in a generic List object and then transferred to the Json extension. The result, a string that looks similar to the one below. It’s trimmed a bit for the information, but it outputs one per school and is ready for consumption by other sources.
Now, to look at converting it back to objects. You COULD convert it to string or something else, but, with how I plan to use it, this would be a situation that I know what is coming down the wire and I’m rebuilding it.
List<School> schoolFromJson = jsonString.FromJson<List<School>>();
foreach (School school in schoolFromJson)
As you can see from the watch below, it recreated (quite quickly) all 102 School objects and repopulated the list.