从WCF RESTful服务反序列化Json对象

时间:2017-12-14 09:25:59

标签: c# wcf

我有WCF RESTful服务声明,如下所示

[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetJson/{id}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
EmployeeJSON GetEmployeeJSON(string id);

我从WCF RESTful Service获取EmployeeJSON对象,如下所示

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;
    }

我从客户端调用WCF RESTful服务,如下所示

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();

我得到json值如下

{"GetEmployeeJSONResult":{"Id":101,"Name":"Sumanth","Salary":5000}}

现在我正在尝试反序列化上面的json,如下所示

JavaScriptSerializer serializer = new JavaScriptSerializer();
Employee responseObject = serializer.Deserialize<Employee>(json);

客户端的Employee类结构如下......

public class Employee
{
    public string Name { get; set; }
    public int Id { get; set; }
    public double Salary { get; set; }
}

但我得到的结果是Id as 0, Name as null and Salary as 0.0

如何反序列化JSON对象?

1 个答案:

答案 0 :(得分:2)

您的Employee类与JSON字符串的结构不匹配。 这堂课是:

public class EmployeeContainer
{
        public Employee GetEmployeeJSONResult { get; set; }
}

...

Employee responseObject = JsonConvert.DeserializeObject<EmployeeContainer>(json)?.GetEmployeeJSONResult;