Search code examples
c#.netjavascriptserializer

JavaScriptSerializer: Cannot deserialize JSON that uses @ symbol in property name


I am using a 3rd party server that exposes an API via REST(so it is not possible to change the JSON). The JSON it returns is in a format like:

    [
         {
              "@noun":"tag",
              "@version":0,
              "@tag":"myFoo"
         }
    ]

I created a C# object to represent this item

    public class ResponseItem
    {
        public string noun {get;set;}
        .....
    }

however, when I try to use the JavaScriptSerializer to deserialize this object, the properties do NOT get assigned. The serializer seems to be unable to handle the properties with the @ symbol in front of the name.

Any ideas on how to solve this?


Solution

  • Ok, so after some finagling, I ditched the JavaScriptSerializer. I switched over to the DataContractJsonSerializer. I then use well defined data contracts and use the DataMember attribute to specify the name.

    i.e.

    [DataContract]
    public class ResponseItem
    {
        [DataMember(Name="@noun")]
        public string Noun {get;set;}
        ....
    }
    

    There may be a better/different way, but this works and is an acceptable solution