One recurring theme that I see in the forums is when a user has a sample JSON document (something that is returned by a service, for example), and he/she wants to deserialize similar JSON documents. That’s the case for most AJAX services which return JSON out there – since there’s no standardized metadata description for JSON, what the sites usually do is to provide a sample response (or request), and the user should infer the schema from that document if he/she wants to work with the data in CLR types (to take advantage of intellisense, static checking, etc). This is similar to the “Paste Xml as Serializable Type” feature which was shipped on the WCF REST Starter Kit, where one would take a sample XML document and the tool would create some types which could be used by the XmlSerializer to consume it.
Using the JsonValue API, I wrote a simple tool which can create a data contract type which can be used with the DataContractJsonSerializer to convert the JSON documents into strongly-typed CLR objects. After loading the JSON into a JsonValue DOM object, the code goes through the tree and creates a System.CodeDom representation of a [ServiceContract] interface with a method which can be used to generate or consume the data. The code will also create CodeDom representations of data contract types which can be used to deserialize the data without needing to go through WCF (i.e., using the DataContractJsonSerializer directly).
For example, given this sample JSON (from the geonames database):
The tool will generate the following classes:
To deserialize that JSON, one could use the “CitiesJsonResponseClass” created above and pass it directly to the DataContractJsonDeserializer:
The tool can be found at http://carlosfigueira.me/JsonUtilities/JsonToContract.htm. I didn’t thoroughly test it, so I’m sure there may be some issues with it. The source code can be found as a sample in the MSDN code gallery. Since the hoster I use for my site only supports partial trust, I had to create a simple CodeDom compiler to go through the CodeDom representation and output the code, but if you’re running the code locally you won’t need to do that – the code has two paths for full and partial trust.
I have a list of some improvements for the tool (serialization only, non-bare operation contracts, WebGet instead of WebInvoke, etc), which I’ll plan on doing in the future. Let me know if you have additional ideas!