govardhan govardhan - 4 months ago 21
JSON Question

Special characters in property name

In my Application a webservice will return a json

{
"UserDetails": [
{
"UserId": "57",
"EmailId": "prasant.sahoo@symphonysummit.com",
"UserName": "Prasant Kumar Sahoo",
"TimezoneMins": "330",
"CustomLogo": "/v51sp8-orglogo-attachments/1.ico",
"IsExecutive": "True",
"HasNTID": "1",
"Org_Id": "1",
"Org_Name": "Summit",
"Designation": null,
"Location": null,
"Location_Name": "",
"WsVersion": "V5.1.0",
"CallMe": "FALSE",
"GPS": "FALSE",
"Feedback_IM&SR": "NULL",
"RPT_Widgets_Access": "False"
}
] }


Here i want to Deserialize this json into a class object. In which the class contains the properties same as the keys in json.

public class UserDetails
{
int? _userId;
string _emailId;
string _userName;
int _timezoneMins;
string _customLogo;
string _isExecutive;
int _hasNTID;
int? _org_Id;
string _org_Name;
string _designation;
int? _location;
string _location_Name;
string _wsVersion;
string _callMe;
string _gPS;
string _feedback_IMSR;
string _rPT_Widgets_Access;
public string Feedback_IM&SR
{
get{return _feedback_IMSR;}
set{_feedback_IMSR = value;}
}

}


Here the variable and property "Feedback_IM&SR" is having '&' character which is not allowed either in variable and Property names,but i need the value of that property.

Can anyone help me on this please.

Answer

Use Netwonsoft.NET:

var details = JsonConvert.DeserializeObject<UserDetails>(json);

For your class, you need to have attributes on your properties for the names:

[JsonProperty(PropertyName = "Feedback_IM&SR")]
string _feedback_imsr { get; set; }

Now you can keep the JSON data having whatever names it wishes to, and have your C# class have another name for the property. And as part of your class, that would look like:

public class UserDetails
{
    int? _userId;
    string _emailId;
    string _userName;
    int _timezoneMins;
    string _customLogo;
    string _isExecutive;
    int _hasNTID;
    int? _org_Id;
    string _org_Name;
    string _designation;
    int? _location;
    string _location_Name;
    string _wsVersion;
    string _callMe;
    string _gPS;
    string _feedback_IMSR;
    string _rPT_Widgets_Access;
    [JsonProperty(PropertyName = "Feedback_IM&SR")]
    public string Feedback_IMSR
    {
       get{return _feedback_IMSR;}
       set{_feedback_IMSR = value;}
    }
}
Comments