monogatari

« no passionate SOAP supporter in Mono yet | Main | You Mono/.NET users do NOT use XML, because you don't really know XML »

System.Json

I read through Scott Guthrie's entry on Silverlight 2.0 beta2 release and noticed that it ships with "Linq to JSON" support. I found it under client SDK. The documentation simply redirects to System.Json namespace page on MSDN.

So, last night I was a bit frustrated and couldn't resist. I'm not sure if MS implementation should work like this yet though.

(You can build it only manually right now; "cd mcs/class/System.Json" and "make PROFILE=net_2_1". The assembly is under mcs/class/lib/net_2_1. You can't do "make PROFILE=net_2_1 install".)

I picked up a sample on another Linq to JSON project to try mine - that is, James Newton-King's JSON.NET. At first, I simply replaced type names and it didn't work. The problematic lines are emphasized below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Json;

using JsonProperty = System.Collections.Generic.KeyValuePair<
    string, System.Json.JsonValue>;

public class Post
{
  public string Title;
  public string Description;
  public string Link;
  public List<string> Categories = new List<string> ();
}

public class Test
{
  public static void Main ()
  {

List<Post> posts = new List<Post> ();
posts.Add (new Post () { Title = "test", Description = "desc",
    Link = "urn:foo" });

JsonObject rss = 
  new JsonObject(
    new JsonProperty("channel",
      new JsonObject(
        new JsonProperty("title", "Atsushi Eno"),
        new JsonProperty("link", "http://veritas-vos-liberabit.com"),
        new JsonProperty("description", "Atsushi Eno's blog."),
        new JsonProperty("item",
          new JsonArray(
            from p in posts
            orderby p.Title
            select (JsonValue) new JsonObject(
              new JsonProperty("title", p.Title),
              new JsonProperty("description", p.Description),
              new JsonProperty("link", p.Link),
              new JsonProperty("category",
                new JsonArray(
                  from c in p.Categories
                  select (JsonValue) new JsonPrimitive(c)
                  ))))))));

Console.WriteLine ("{0}", rss);
JsonValue parsed = JsonValue.Parse (rss.ToString ());
Console.WriteLine ("{0}", parsed);

  }
}

Unlike Linq to JSON in JSON.NET, JsonObject and JsonArray in System.Json do not accept System.Object as argument. Instead, it requires strictly-typed generic IEnumerable of JsonValue. That is, for example, IEnumerable<JsonPrimitive> is invalid. Thus I was forced to add explicit cast in my linq expression.

It may be improved in SL2 RTM though. Linq to XML classes accept System.Object argument to make it simple (and well, yes, sort of error-prone).

|