【问题标题】:Deserialize Json object from WCF RESTful Service从 WCF RESTful 服务反序列化 Json 对象
【发布时间】:2017-12-14 17:48:45
【问题描述】:

我有如下 WCF RESTful 服务声明

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

我从 WCF RESTful 服务获得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 对象?

【问题讨论】:

  • 您的 JSON 字符串描述了一个具有一个属性的对象:GetEmployeeJSONResult,它是一个 Employee 对象:public class tempObject{public Employee GetEmployeeJSONResult{get;set;}}

标签: c# wcf


【解决方案1】:

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

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

...

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

【讨论】:

  • 能否请您删除第二个代码中的问号?
  • 如果 WCF RESTful 服务在此处返回员工列表,代码会是什么?
  • 那个?用于防止 NullReferenceException 是的,如果您提供带有 List 数据的示例 JSON 字符串,我可以调整代码。
猜你喜欢
  • 1970-01-01
  • 2015-02-13
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多