ASP.NET WebMethod Returns JSON wrapped in quotes

前端 未结 3 1432
挽巷
挽巷 2020-12-15 00:53

I have an asp.net page with a WebMethod on it to pass JSON back to my javascript.

Bellow is the web method:

[WebMethod]
public static string getData         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 01:33

    I assume that you want to return the JSON representation of the object

     {
        firstname:"John",
        lastname:"Smith"
     }
    

    but your method signature is returning a string. The ASP.Net framework serialisation is correctly serialising the string response. Put another way, if your function was

    string response = "foo";
    return response; 
    

    You would not be surprised if the output was

    {"d":{"foo"}}
    

    It just happens that response has double quotes that need to be escaped.

    You obviously just want to get at the object. You have 2 options: -

    1) use eval in your javascript to turn the string into an object e.g.

    function onSuccessCallback(retval) {
         var obj = eval(retval.d);
    }`
    

    2) or (and this is my prefered solution) have your method return an actual object and let the JSON serialisationof the framework do the heavy lifting for you

    [WebMethod]
    public static object getData(Dictionary d) {
        var response = new { firstname = "John", lastname="Smith" };
        return response;
    }
    

    You will see that this generates the response that you probably originally expected (e.g. {"d":{"firstname":"John", "lastname":"Smith"}}

提交回复
热议问题