Search code examples
c#regexjsonwindows-phone-7json.net

Filter out character out of returned JSON object


I'm busy developing an app for Windows Phone 7. The app basically calls a web service that then returns JSON content. I use the Json.NET library to then take that JSON object that then gets converted to a C# object. For example, if the JSON content looked like this:

      {
           "FirstName" : "",
           "LastName" : "",
           "Gender" : ""
      }

A class would get created that looks like:

class person{
   public string FirstName {get;set;}
   public string LastName {get;set;}
   public string Gender {get;set;}
}

So as you can see, the variables in the generated class matches the variables names in the JSON content exactly. E.g., FirstName → FirstName.

But now I've come to a stage where the returned JSON content has a variable with the name 'ID#', and if you're a quick thinker you'll see that a C# variable is then going to get generated that will be named 'ID#', but obviously in C# you can't use the hash symbol in a variable name.

How can I get past this obstacle? I was thinking of filtering out the # symbols in the returned JSON content, but how exactly do I go about doing this, and is that even the right thing to do?


Solution

  • Try to write:

    class person{
       [JsonProperty("ID#")]
       public string ID { get; set;}
       public string FirstName {get;set;}
       public string LastName {get;set;}
       public string Gender {get;set;}
    }