Reputation: 1150
I have WCF RESTful Service declaration as below
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetJson/{id}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
EmployeeJSON GetEmployeeJSON(string id);
I get EmployeeJSON
object from WCF RESTful Service as below
public EmployeeJSON GetEmployeeJSON(string id)
{
List<EmployeeJSON> employees = new List<EmployeeJSON>()
{
new EmployeeJSON() {Name="Sumanth",Id=101,Salary=5000.00 },
new EmployeeJSON() {Name="Ehsan",Id=102,Salary=6000.00 },
};
var Employee = (from x in employees
where x.Id.ToString() == id
select x);
return Employee.FirstOrDefault() as EmployeeJSON;
}
I call the WCF RESTful service from client as below
var request = (HttpWebRequest)WebRequest.Create("http://localhost:1249/Service1.svc/GetJson/101");
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string json = reader.ReadToEnd();
And I get json
value as follows
{"GetEmployeeJSONResult":{"Id":101,"Name":"Sumanth","Salary":5000}}
Now I am trying to Deserialize the above json
as follows
JavaScriptSerializer serializer = new JavaScriptSerializer();
Employee responseObject = serializer.Deserialize<Employee>(json);
The Employee class structure is as follows at client side...
public class Employee
{
public string Name { get; set; }
public int Id { get; set; }
public double Salary { get; set; }
}
But the result I am getting is Id as 0, Name as null and Salary as 0.0
How can I deserialize the JSON
object?
Upvotes: 1
Views: 1102
Reputation: 553
Your Employee class didnt match the structure of the JSON string. This class is:
public class EmployeeContainer
{
public Employee GetEmployeeJSONResult { get; set; }
}
...
Employee responseObject = JsonConvert.DeserializeObject<EmployeeContainer>(json)?.GetEmployeeJSONResult;
Upvotes: 2