Inferring schemas for JSON

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).

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!

This is a great little project, i love the use of codedom to generate the serializer – classy stuff. Thanks a lot btw, im using this post / code to create messaging objects for JSend ( labs.omniti.com/…/jsend )

Bragaadeesh, this implementation is similar. This one creates, in addition to the data types, also a service contract and an operation contract which can be used directly, while that one only creates the data type.