The Geocortex Essentials REST API (written for the upcoming 2.0 release) relies heavily on the ability to serialize objects to JSON (JavaScript Object Notation). JSON is used as a stateless response to an HTTP request for a REST resource; whether generated by the ArcGIS Server JavaScript API, Flex API, or other (Silverlight for example).

One of the interesting things about serializing server-side, .NET objects (to JSON or any format for that matter) is the way in which we determine which properties are serialized. Most automatic serialization mechanisms (implementing ISerializable for example) require that all components of a class are themselves serializable and simply convert the entire object into its serialized representation.

Sometimes; however, you may want two different serialized representations for the same object. For example, when serializing a Geocortex.Essentials.Map object, we may want to know the name and type of each Geocortex.Essentials.Layer within that Map; however, if serializing just an individual Layer we may wish to get a more "verbose" representation including its extent, visibility, or other properties.

Joel (Geocortex Essentials Product Developer) introduced me to a handy way of easily serializing an object to JSON for this scenario. Using the JavaScriptSerializer object (from the MS AJAX library), you can simply serialize a Dictionary containing key/value pairs and the result is a JSON string representing just those properties you wish to serialize. If the order of your properties is important, you could also use an OrderedDictionary.

Consider, for example, this "Person" object, containing an associating with an "Address" object.

PersonAddress

Now, if I want to serialize the person to JSON while explicitly selecting the components I’m interested in, I can create a Dictionary as follows (assuming I have a variable named "person" which is assigned to a Person object as depicted above):

jsonPart1

Serializing the dictionary is accomplished easily with this line of code:

jsonPart2

And the result is a nice JSON string which is exactly what I was looking for:

{
    "name" : "Smith, John",
    "address" : "123 Main St., New York, NY"
}

Note; however, that the same handy conversion "trick" is not available when using the DataContractJsonSerializer (from the WCF library in .NET 3.5):

jsonPart4

The DataContractJsonSerializer creates a much more explicit representation of my Dictionary (an array of key/value pairs) which isn’t as useful when using JavaScript to parse and evaluate the JSON:

[
   {
        "Key" : "name",
        "Value" : "Smith, John"
    },
    {
        "Key" : "address",
        "Value" : "123 Main St., New York, NY"
    }
]

In case you’re interested, the JavaScriptSerializer was deprecated in .NET 3.5 (which is odd since it was made available in MS AJAX 1.0); however, it has been de-deprecated in .NET 3.5 SP1.