Thursday, February 23, 2012

Annotation in C# for mapping JsonProperty to a variable

If for some reason you are .NET Framework 2.0 and using Newtonsoft.Json libray than this is gonna be very useful.
You have a case where your Json property contains a '-' sign, than obviously you can't have a C# variable to map the same as variable naming scheme does not allow - signs.

I recently faced a similar problem and spent hours googling to figure out how to do it in .net 2.0 but all the efforts were in vain. Than after a lot of hit and trial and reading source files I hit this annotation JsonProperty("my-name") and hurray it worked. Just to provide a small example usage:

JSON:
{"my-name" : "Biplav"}

C# snippet:

public class Name
{
   private String m_my_name;


   [JsonProperty("my-name")]
   public String my_name 
  {
      get { return m_my_name;}
      set  { m_my_name = value;}
  }