Silverlight で JSON を扱う方法が意外に簡単で驚いた

System.Json 名前空間内のクラスを使えばいい。下記は JSON オブジェクトを扱うサンプル。

string json = "{ \"id\": 1, \"name\": \"sample\" }";
JsonObject value = (JsonObject)JsonObject.Parse(json);

var message = new StringBuilder();
foreach (var key in value.Keys)
{
    message.AppendFormat("key:{0}, value:{1}", key, value[key]);
    message.AppendLine();
}
MessageBox.Show(message.ToString());

配列を扱うときはこんな感じ。

string json = "[{ \"id\": 1, \"name\": \"foo\" }, { \"id\": 2, \"name\": \"bar\" }]";
JsonArray array = (JsonArray)JsonArray.Parse(json);

var message = new StringBuilder();
foreach (JsonObject value in array)
{
    foreach (var key in value.Keys)
    {
        message.AppendFormat("key:{0}, value:{1}", key, value[key]);
        message.AppendLine();
    }
}
MessageBox.Show(message.ToString());

WebClient の DownloadStringAsync と組み合わせると、Web API を呼び出して取得した JSON を簡単に扱える。

WebClient client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
    JsonArray result = (JsonArray)JsonArray.Parse(e.Result);

    // JsonArray を使って何かする
};
client.DownloadStringAsync(address);

簡単に扱えるけど、Silverlight をホストするサービスが .NET 以外の言語で実装されている時しか使い道が無いね。

サービスを .NET で開発する場合は、Silverlight とのデータのやり取りは WCF RIA Service や WCF Data Service を選択するだろうから。