ASP.NET WebService is Wrapping my JSON response with XML tags

前端 未结 6 1098
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 11:49

I\'m not sure where I\'m going wrong of what I\'m missing.

I\'m building an ASP.NET 2.0 (on the .Net 3.5 framework) Web application and I am including a webservice.

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 12:12

    Three things you may not be doing:

    • Marking the method static
    • Performing a POST
    • Hand an empty "{ }" for the data in jQuery.

    There may be a way to call the method with a GET, I've only ever used POST. I was able to get your example working with this:

    
    
    

    The code behind (you don't need to create a webservice, you can put this in your default.aspx):

    [WebMethod]
    public static string Tester()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
    
        var jsonData = new
        {
            total = 1, // we'll implement later 
            page = 1,
            records = 3, // implement later 
            rows = new[]{
                  new {id = 1, cell = new[] {"1", "-7", "Is this a good question?", "yay"}},
                  new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?", "yay"}},
                  new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?", "yay"}}
                }
            };
    
        return ser.Serialize(jsonData); //products.ToString();
    }
    

    The result:

    {"d":"{\"total\":1,\"page\":1,\"records\":3,\"rows\":[{\"id\":1,\"cell\":[\"1\",\"-7\",\"Is this a good question?\",\"yay\"]},{\"id\":2,\"cell\":[\"2\",\"15\",\"Is this a blatant ripoff?\",\"yay\"]},{\"id\":3,\"cell\":[\"3\",\"23\",\"Why is the sky blue?\",\"yay\"]}]}"}
    

    A more detailed explanation is here

提交回复
热议问题