To know more about JSON format, check out the http://www.json.org - To quote,
JSON (J avaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. These properties make JSON an ideal data-interchange language.
Understanding JSON
In JSON, any object can be serialized to
- A collection of name/value pairs. (For eg, from C# point of view, a simple example is Dictionary
)</STRING,STRING> - An ordered list of values. (An array or a list)
URL: http://search.twitter.com/trends/current.json - You may get something like this as reply (I've shortened it a bit :)).
{ "as_of" : 1256965326,
"trends" : { "2009-10-31 05:02:06" :
[
{ "name" : "Happy Halloween",
"query" : "\"Happy Halloween\" OR #Halloween"
},
{ "name" : "#foofighterslive",
"query" : "#foofighterslive"
},
{ "name" : "#Backnthedaycartoon",
"query" : "#Backnthedaycartoon"
},
{ "name" : "Follow Friday",
"query" : "\"Follow Friday\""
}
] }
}
And for your information, here is a quick Online Json Formatter to format your JSON data a bit so that it'll look pretty
JSON In Silverlight
JSON serialization support is provided in Silverlight for long time. Let us have a close look at how an object gets serialized to JSON. Consider a simple Human class.
public class Human
{
public List Children { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Let us create a simple Human object and try serializing the same.
var human = new Human() { Name = "Joe", Age = 10 };
If you serialize the human object using JSON serializer, you'll get something like
{"Age":10,"Children":null,"Name":"Joe"}
You may find that each property/value is represented using a Key Value pair. Now, Let us try with an object graph.
var human = new Human()
{
Name = "Joe", Age = 30 ,
Children = new List<Human>
{
new Human() {Name="Jim", Age=3},
new Human() {Name="July", Age=2}
}
};
And here is the result if you serialize the human object now. Note how the elements in Children collection of human object is serialized and represented in JSON.
{ "Age" : 30,
"Children" : [ { "Age" : 3,
"Children" : null,
"Name" : "Jim"
},
{ "Age" : 2,
"Children" : null,
"Name" : "July"
}
],
"Name" : "Joe"
}
Serialization and De-Serialization In Silverlight
Now, let us get back to the initial point, how to serialize and deserialize objects to/from JSON in Silverlight? You may use these extension methods I've put together. They are pretty straight forward. The first method adds an extension method to strings for deserializing them, and the second one adds an extension methods to objects for serializing them.
using System;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
namespace JSONHelper
{
public static class JsonSerializerHelper
{
/// <summary>
/// Adds an extension method to a string
/// </summary>
/// <typeparam name="TObj">The expected type of Object</typeparam>
/// <param name="json">Json string data</param>
/// <returns>The deserialized object graph</returns>
public static TObj JsonDeserialize<TObj>(this string json)
{
using (MemoryStream mstream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(TObj));
return (TObj)serializer.ReadObject(mstream);
}
}
/// <summary>
/// Serialize the object to Json string
/// </summary>
/// <param name="obj">Object to serialize</param>
/// <returns>Serialized string</returns>
public static string JsonSerialize(this object obj)
{
using (MemoryStream mstream = new MemoryStream())
{
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(obj.GetType());
serializer.WriteObject(mstream, obj);
mstream.Position = 0;
using (StreamReader reader = new StreamReader(mstream))
{
return reader.ReadToEnd();
}
}
}
}
}
You may import JSONHelper namespace to use these extension methods, like this. Caution: Please make sure that you've valid JSON string or a serializable object when you use these methods
var human = new Human()
{
Name = "Joe", Age = 30 ,
Children = new List
{
new Human() {Name="Jim", Age=3},
new Human() {Name="July", Age=2}
}
};
//Serialize the object.
var hstr = human.JsonSerialize();
//Create a cloned object by deserializing the same
var cloned = hstr.JsonDeserialize<Human>();
Alright, that is it for now. Enjoy coding.

