Tuesday, 2 December 2014

JSON serialisation/deserialisation with snake_case naming conventions

GitHub (NuGet package source)
GitHub (Usage example)
Nuget Package

JSON is quickly becoming the norm for data transfer along the HTTP protocol and for many of us it is a daily task to serialise into and from JSON.

The problem with JSON, however, is the fact that there is no standard associated with its naming conventions. Let me give you an example.

Below is a snipet of JSON from the Twitter API:

 {  
   "id": 85011021,   
   "id_str": "85011021",   
   "name": "Raph",   
   "screen_name": "RaphHaddadAus",   
   "location": "Sydney",   
   "profile_location": null  
 }  

And here is JSON from the Google + API:

 {  
    "objectType": "person",  
    "id": "104264388447663009734",  
    "displayName": "Raphael Haddad"  
 }  

As you can see there is no consistency between the property names in each of the examples. This issue is quite widespread and some providers have their properties as snake_case, others are camelCase and others are PascalCase

What makes things even more complicated is that there are different standards within some naming conventions as well. Let's take snake_case as an example:

Below are two naming conventions that can be written in snake_case:
  • page_section2
  • page_section_2

So how do we serialise to and from objects in C# while maintaining statically typed classes with proper C# naming conventions?