I am using jquery to call an ajax wcf method that returns a list of objects as a JSON string. The JSON string looks like this when inspecting it in fiddler2 (in TextView):>
I assume you want to return the value of ser.Serialize(query.ToArray())
to the client (an array). But you're returning it as a string, so WCF will escape that JSON into a string, and what you'll end up is not an array, but a string.
Since you're using anonymous types, which aren't natively supported by WCF, you need to use the JavaScriptSerializer
. So to prevent the double-encoding of the JSON (into the string) you should return the data as a Stream
instead, so that WCF won't touch your data (see sample code below).
One more thing: I see your response has a {"d":...}
wrapper, which suggests that you're using the
/ WebScriptEnablingBehavior
/ WebScriptServiceHostFactory
when defining your service / endpoint. Since you're not using the ASP.NET AJAX library, you don't need that wrapping, so you can use the "simpler"
/ WebHttpBehavior
/ WebServiceHostFactory
instead, and your response won't be wrapped in that "d" object.
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public System.IO.Stream GetPeople(Guid groupId)
{
using (SchedulerContext context = new SchedulerContext())
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var query = from p in context.People
where p.Group_ID == groupId
select new
{
p.ID,
p.Name,
p.Surname
};
string json = ser.Serialize(query.ToArray());
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return ms;
}
}