Sunday, November 28, 2010

Working with JSON Values that are C# Reserve Words.

While playing around with GitHub’s API for Gists, I discovered I couldn’t simply deserialize into an object because the API used the C# reserve word “public” as a property name. Luckily, the DataMember attribute has a “Name” property that allows to you explicitly map a JSON property to your object’s property of a different name:

   1:  namespace MyGistClient
   2:  {
   3:      [DataContract]
   4:      public class GistsResult
   5:      {
   6:          ...
   7:   
   8:          [DataMember(Name = "public")]
   9:          public bool IsPublic { get; set; }
  10:   
  11:          ...
  12:      }
  13:  }

While C# will let me make a property named “Public”, I decided to use “IsPublic” instead so I don’t have any issues if my object gets consumed by another .NET language that isn’t case sensitive.

2 comments:

  1. Hey! This looks familiar :-)

    ReplyDelete
  2. Yes, a special shout-out to vcsjones (http://twitter.com/vcsjones) who showed me what I was doing wrong in my Attribute.

    ReplyDelete

Note: Only a member of this blog may post a comment.

Follow me on App.net