2012-02-16 101 views
9

我對RESTful WCF服務非常新,所以請耐心等待。我正在嘗試構建一個簡單的RESTful WCF服務,它返回一個學生列表作爲json響應。所有工作都很好,直到我嘗試將json字符串轉換回客戶端上的Student對象列表。REST風格的WCF包裝方法名稱的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":"[email protected]","ID":1,"Name":"Vinod"}]} 

出於某種原因,json響應正在被包裝在FetchStudentsResult中。現在在調試模式下,如果我強制刪除這個FetchStudentsResult包裝,我的反序列化工作完全正常。

我試過DataContractJsonSerializer,但結果完全一樣。有人能告訴我我錯過了什麼嗎?

回答

22

好吧,我已經弄清楚了。問題是以下行:

BodyStyle = WebMessageBodyStyle.Wrapped 

當我把它改爲:

BodyStyle = WebMessageBodyStyle.Bare 

一切完美的作品!

謝謝!

+0

謝謝維諾德您的解決方案幫助我;你是一個拯救生命的人。 – 2013-03-14 05:46:35