【发布时间】:2012-03-07 22:30:43
【问题描述】:
我对 RESTful WCF 服务还很陌生,所以请多多包涵。我正在尝试构建一个简单的 RESTful WCF 服务,该服务将学生列表作为 json 响应返回。一切正常,直到我尝试将 json 字符串转换回客户端上的学生对象列表。
这是我的运营合同:
[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 中。现在在调试模式下,如果我强行删除这个 FetchStudentsResult 包装,我的反序列化工作得非常好。
我尝试过 DataContractJsonSerializer,但结果完全一样。谁能告诉我我错过了什么?
【问题讨论】: