Handy Trick for JSON Serialization
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.
Consider, for example, this "Person" object, containing an associating with an "Address" object.
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):
Serializing the dictionary is accomplished easily with this line of code:
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):
"Key" : "name",
"Value" : "Smith, John"
"Key" : "address",
"Value" : "123 Main St., New York, NY"