我对 RESTful WCF 服务还很陌生,所以请耐心等待。我正在尝试构建一个简单的 RESTful WCF 服务,该服务将学生列表作为 json 响应返回。一切正常,直到我尝试将 json 字符串转换回客户端上的 Student 对象列表为止。
这是我的操作契约(Contract):
[OperationContract]
[WebGet(UriTemplate = "Students/", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
public List<Student> FetchStudents()
{
//Fetch and return students list
}
客户端代码:
static void Main(string[] args)
{
HttpClient client = new HttpClient("http://localhost/StudentManagementService/StudentManagement.svc/");
response = client.Get("Students/");
response.EnsureStatusIsSuccessful();
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
string str = response.Content.ReadAsString();
List<Student> st = json_serializer.Deserialize<List<Student>>(str);
}
这段代码显然失败了,因为服务返回的 json 字符串如下所示:
{"FetchStudentsResult":[{"Course":"BE","Department":"IS","EmailID":"b@gmail.com","ID":1,"Name":"Vinod"}]}
出于某种原因,json 响应被包裹在 FetchStudentsResult 中。现在在 Debug模式下,如果我强行删除这个 FetchStudentsResult 包装,我的反序列化工作得很好。
我试过 DataContractJsonSerializer 但结果完全一样。有人能告诉我我错过了什么吗?
最佳答案
好吧,我自己想通了。问题是以下行:
BodyStyle = WebMessageBodyStyle.Wrapped
当我将其更改为:
BodyStyle = WebMessageBodyStyle.Bare
一切正常!
谢谢!
关于wcf - RESTful WCF 用方法名称包装 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9312752/