jquery ajax call return JSON parsing error

前端 未结 5 1283
走了就别回头了
走了就别回头了 2020-12-30 23:14

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):

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 00:10

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

提交回复
热议问题