In my Application a webservice will return a json
{
"UserDetails": [
{
"UserId": "57",
"EmailId": "[email protected]",
"UserName": "Prasant",
"TimezoneMins": "330",
"CustomLogo": "",
"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 _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.
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;}
}
}
you can all each property however you want, but in the C# implelmentation write it down like this:
class UserDetails
{
[JsonProperty ("Feedback_IM&SR")]
public string FeedbackProperty{ get; set; }
}
If you the "JsonProperty" attribute above the property, the serializer will know that in the JSON, the property's name is the one stated in the attribute
You can make class objects from json using following references
http://json2csharp.com/
Just paste your json string and it will generate C# class and properties inside that json.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With