11

I am pretty new to RESTful WCF services so bear with me. I am trying to build a simple RESTful WCF service that returns a List of Students as json response. All works well until the point where I try to convert the json string back to list of Student objects on the client.

Here is my operation contract:

[OperationContract]
[WebGet(UriTemplate = "Students/", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
public List<Student> FetchStudents()
{
//Fetch and return students list
}

Client code:

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);
}

This code obviously fails because the json string returned by the service looks like below:

{"FetchStudentsResult":[{"Course":"BE","Department":"IS","EmailID":"b@gmail.com","ID":1,"Name":"Vinod"}]}

For some reason the json response is getting wrapped inside the FetchStudentsResult. Now in debug mode if I forcefully remove this FetchStudentsResult wrap, my deserialization works perfectly fine.

I have tried DataContractJsonSerializer but the result is exactly the same. Can someone tell me what am I missing?

Will Hartung
  • 115,893
  • 19
  • 128
  • 203
Vinod
  • 929
  • 1
  • 16
  • 42

2 Answers2

26

Ok, I have figured it out myself. The problem is the below line:

BodyStyle = WebMessageBodyStyle.Wrapped

When I changed this to:

BodyStyle = WebMessageBodyStyle.Bare

Everything works perfectly!

Thanks!

Steve B
  • 36,818
  • 21
  • 101
  • 174
Vinod
  • 929
  • 1
  • 16
  • 42
1

In my case, It was WebInvoke instead of WebGet and I was sending data in body. Because of that this solution didnt work for me. I have used the one below and it worked.

BodyStyle = WebMessageBodyStyle.RequestWrapped

So in post, the body should be wrapped but no need in response. Thanks for the questioner and his answer for giving a clue about this problem.

smoothumut
  • 3,423
  • 1
  • 25
  • 35