- Accessing JSON data
- Accessing XML nodes and attributes
- Experimenting and calling into with REST services without an explicitly coded up proxy
- Access to settings (eg. Isolated storage settings in Silverlight, or configuration settings such as appSettings)
- ... and more
Traditional dynamic languages are striving to introduce some degree of static typing (eg. type information in ActionScript 3, and the unfortunately failed EcmaScript 4 attempt) for perf and more appeal. On the flip side, C# is evolving nicely by introducing dynamic typing through a static type called dynamic (nice oxymoron) and offering not just a nicer syntax, but a much more intuitive model for these scenarios. I can only wish the C# 4.0 was here now!
Anyway, I am still excited about this feature, and given the VS 2010 and C# 4.0 CTP are available, I decided to play with a few of the above listed scenarios. In this post, I'll describe the JSON scenario, and in a subsequent post, I'll write about the REST services scenario, so stay tuned and come back for more.
First a quick look at how JSON data might be used in the framework today, specifically using System.Json in Silverlight.
string jsonText = "{ xyz: 123, items: [ 10, 100, 1000 ] }";Contrast this with using dynamic typing. I basically took my very light-weight JSON reader and writer and added support for dynamic typing in my equivalent JsonObject and JsonArray types. With that in place, I can now write code as follows:
JsonObject jsonObject = (JsonObject)JsonValue.Parse(jsonText);
JsonArray items = (JsonArray)jsonObject["items"];
items[2] = 1001;
JsonObject bar = new JsonObject();
bar["name"] = "c#";
jsonObject["bar"] = bar;
StringWriter sw = new StringWriter();
jsonObject.Save(sw);
string newJsonText = sw.ToString();
string jsonText = "{ xyz: 123, items: [ 10, 100, 1000 ] }";
JsonReader jsonReader = new JsonReader(jsonText);
dynamic jsonObject = jsonReader.ReadValue();
dynamic items = jsonObject.items;
items.Item(2, 1001);
dynamic bar = new JsonObject();
bar.name = "c#";
jsonObject.bar = bar;
JsonWriter writer = new JsonWriter();
writer.WriteValue((object)jsonObject);
string newJsonText = writer.Json;
Note that in the CTP, there isn't any support for indexers used against dynamic types, which gets in the way of normal array syntax. Hence the workaround above using Item(). However, I've been told, that support for indexing into dynamic types already exists in later builds.
Personally, I think the resulting code using dynamic typing is nicer than the current System.Json APIs, since you don't have to use strings for member names, and that distinguishes them from actual string values. Thoughts?

没有评论:
发表评论