System.Json improvements
Yesterday the WCF team released a new version of the “WCF Support for jQuery” libraries on codeplex (https://wcf.codeplex.com). Besides some bug fixes, we added some new features to make the JSON API better. Here’s a short list of them:
Events
Similarly to the XElement API, JsonValue now supports events as well, so that a user can register to be notified when a JsonValue instance is modified. Notice that JsonPrimitives are immutable, since we don’t allow the modification of the wrapped CLR object, and all types supported in JsonPrimitive are immutable themselves (numbers, boolean, char, strings, DateTime, DateTimeOffset and Uri). So the event will essentially be raised only on JsonArray and JsonObject instances.
Like the XElement type, JsonValue exposes two events: Changing and Changed. The first is raised when a change is about to be made – and that gives the user some control to prevent the change from happening, like in the example below.
- public class JsonObjectWithValidation
- {
- public static void Test()
- {
- JsonObject jo = new JsonObject
- {
- { "name", "John" },
- { "age", 34 }
- };
- jo.Changing += new EventHandler<JsonValueChangeEventArgs>(ValidateAge);
- Console.WriteLine("Original age: {0}", jo["age"]);
- jo["age"] = 35; // valid
- Console.WriteLine("New age: {0}", jo["age"]);
- try
- {
- Console.WriteLine("Trying to set the age to an invalid value");
- jo["age"] = 355;
- }
- catch (InvalidOperationException e)
- {
- Console.WriteLine(e.Message);
- }
- Console.WriteLine("New age: {0}", jo["age"]);
- Console.ReadLine();
- }
- static void ValidateAge(object sender, JsonValueChangeEventArgs e)
- {
- JsonObject jo = sender as JsonObject;
- if (e.Key == "age")
- {
- if (e.Change == JsonValueChange.Add || e.Change == JsonValueChange.Replace)
- {
- // age needs to be an integer between 0 and 150
- int newAge = e.Child.ReadAs<int>(-1);
- if (newAge < 0 || newAge > 150)
- {
- throw new InvalidOperationException("'Age' field must have a value between 0 and 150!");
- }
- }
- }
- }
- }
The second event, Changed, is raised after the change is made. The main scenario for it is to bind a JsonValue instance to an UI control. Whenever changes are made, we can update the UI based on the new value. One of the samples included in the download package (Features / JsonValueEvents) shows one way it can be done.
Exposing the wrapped CLR type
A small feature that we didn’t have before, we now expose a get-only property in JsonPrimitive that returns the CLR object which was wrapped by that instance. We’ve had converters (casts, ReadAs and TryReadAs) before so that you could ask for a CLR object from the JsonPrimitive, but there are cases where you don’t actually know the type – for example, if you want to clone the JSON DOM. This can now be done with a simple extension method, like the one shown below.
- public static class JsonValueCloneExtension
- {
- public static JsonValue Clone(this JsonValue value)
- {
- if (value == null)
- {
- return null;
- }
- switch (value.JsonType)
- {
- case JsonType.Default:
- return value; // only 1 Default instance
- case JsonType.Boolean:
- case JsonType.Number:
- case JsonType.String:
- // It's a JsonPrimitive
- JsonPrimitive jp = (JsonPrimitive)value;
- JsonPrimitive newPrimitive;
- JsonPrimitive.TryCreate(jp.Value, out newPrimitive); // we know it will succeed, since the value came from a JsonPrimitive itself
- return newPrimitive;
- case JsonType.Array:
- JsonArray newArray = new JsonArray();
- JsonArray ja = (JsonArray)value;
- foreach (JsonValue jv in ja)
- {
- newArray.Add(Clone(jv));
- }
- return newArray;
- default:
- // It's a JsonObject
- JsonObject newObject = new JsonObject();
- JsonObject jo = (JsonObject)value;
- foreach (KeyValuePair<string, JsonValue> item in jo)
- {
- newObject.Add(item.Key, Clone(item.Value));
- }
- return newObject;
- }
- }
- }
Operations and conversions in dynamic notation
In an effort to make Javascript users more at ease in dealing with JsonValue instances, we’ve improved the dynamic support in JsonValue to make certain operations more natural in the dynamic world. Among those operations:
- Implicit conversions to primitive types (no need to cast)
- Operators support – a dynamic reference to a JsonPrimitive can now be used in addition, subtraction, relational operations, etc.
The code below shows some examples of that. The sample included in the download package (Features / JsonValueDynamic) also shows more instances of that.
- public class JsonValueAndDynamics
- {
- public static void Test()
- {
- dynamic ja = new JsonArray
- {
- new JsonObject
- {
- { "Name", "John" },
- { "DOB", new DateTime(1984, 01, 17) },
- { "Salary", 90000.00 },
- { "IsMarried", false },
- },
- new JsonObject
- {
- { "Name", "Joe" },
- { "DOB", new DateTime(1983, 02, 18) },
- { "Salary", 105000.00 },
- { "IsMarried", true },
- },
- };
- for (int i = 0; i < ja.Count; i++)
- {
- string name = ja[i].Name;
- if (ja[i].IsMarried)
- {
- Console.WriteLine(name + " is married");
- }
- else
- {
- Console.WriteLine(name + " is not married");
- }
- Console.WriteLine(name + " earns " + (ja[i].Salary > 100000 ? "more" : "less") + " than 100k per year");
- }
- Console.ReadLine();
- }
- }
What next?
Download the new release (at https://wcf.codeplex.com/releases/view/57702) and tell us what you think. We’ll look for addressing any issues that are raised in our next release.
Comments
- Anonymous
March 06, 2011
I made this comment somewhere I dont remember but using the phase "WCF Support for jQuery" is misleading. The tool will work with any javascript library with the right http headers and data in the request. Why call it "WCF Support for jQuery". - Anonymous
March 15, 2011
You got a good point - even internally in the team we've debated among ourselves about the naming of this - some of the other suggestions were along the lines of "WCF Javascript Support". Most of our samples use jQuery, and there are some jQuery-specific improvements which the team has been working on, which hould come live over the next few months, however, and that should make the name more meaningful when that happens. Thank you for the feedback!