如何从WCF Restful Service反序列化Json响应?

时间:2014-12-15 08:57:23

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

我想将Json响应反序列化为我的类对象。我已经创建了一个WCF Restful Service,并且从客户端使用代理对象我调用了一个返回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中的控制器发出请求:

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

但是我的端点在config中,

enter image description here

2 个答案:

答案 0 :(得分:1)

class GetProjectResultWrapper
    {
        public GetProjectResult GetProjectResult{ get; set; }
    }
    class GetProjectResult 
    {
        public string id {get;set;}
        .....
        ......
    }
JavaScriptSerializer ser = new JavaScriptSerializer();
    GetProjectResultWrapper response = ser.Deserialize<GetProjectResultWrapper>(sb.ToString());
response .GetProjectResult;

答案 1 :(得分:1)

您可以使用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;