json - 如何反序列化 WCF Restful 服务的 Json 响应?

标签 json wcf asp.net-mvc-4 rest

我想将 Json 响应反序列化到我的类对象中。我创建了一个 WCF Restful 服务,并从使用代理对象的客户端调用一个服务方法,该方法返回一个 json。现在我想将该 json 转换为我的类对象。 我的服务如下:

[OperationContract]
    [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "GetProject/{projectID}")]
    tblProject GetProject(String projectID);

实现:

public tblProject GetProject(String projectID)
        {
            tblProject pro = new tblProject();
            pro = DAL.ProjectDAL.GetProject(Convert.ToInt32(projectID));
            return pro;
        }

并且从 MVC 中的 Controller 我发出请求:

public ActionResult Index()
        {
            var request = (HttpWebRequest)WebRequest.Create("http://localhost:8733/Design_Time_Addresses/RestServiceLibrary.RESTService/REST_ProjectService/getproject/2");
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
                string txtResult = reader.ReadToEnd();
return view();
    }

当我运行时,我得到的响应为:

enter image description here

当我通过代理方法调用时,出现异常:

enter image description here

但我的端点在配置中,

enter image description here

最佳答案

您可以使用javascriptserializer

string s = "YouJsonText";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize(s);
//or
YouCustomClass res = serializer.Deserialize<YouCustomClass>(sb.ToString());

此外,您可以像这样使用 CustomJsonConverter:

public class YouCustomClassConverter : JavaScriptConverter
{
  public override object Deserialize(IDictionary<string, object> dictionary, Type type,                      JavaScriptSerializer serializer)
  {
      throw new NotImplementedException();
  }

  public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
  {
      throw new NotImplementedException();
  }

   //and first you need register type, which you want Deserialize
   public override IEnumerable<Type> SupportedTypes
   {
      get { return new[] { typeof(YouCustomClass ) }; }
   }

}

//and then example of using JavaScriptSerializer with custom converter
var ser = new JavaScriptSerializer();
ser.RegisterConverters(new JavaScriptConverter[] { new YouCustomClassConverter() });
try
{
     YouCustomClass obj = ser.Deserialize(jsonString);
}

注意:您需要使用using System.Web.Script.Serialization;

关于json - 如何反序列化 WCF Restful 服务的 Json 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27480392/

相关文章:

c# - MVC 4 如何正确地将数据从 Controller 传递到 View

java - Retrofit2 数据模型 - 列表有问题

javascript - @RequestBody 通过 Spring MVC JSON Jackson 处理器发送

iOS:如何获取带有\"\字符的 JSON 数据?

wcf - 配置 WCF 客户端绑定(bind)以在 dotnet core 2.2 中使用 X509 证书

c# - 如何向 WCF session 添加值并在客户端 (WinForm) 和 WCF 上下文中使用它?

c# - Asp.net mvc 项目发布后出现内部服务器错误

c# - 使用新值更新现有对象

java - 在 recyclerview 中访问 JSON 数组中的项目成员

wcf - 如何替换 Web Api 堆栈中的 DataContractResolver?