ASP.NET JSON Web服务始终返回包含在XML中的JSON响应

Joh*_*ode 12 xml json asmx

我看到了类似的问题,但它没有解决我的问题.我在ASMX文件中有一个JSON Web服务;

Web方法的代码

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetUserRoles(string JSONUserCode)
        {
            string retRoles = string.Empty;
            List<JSONRole> roles = new List<JSONRole>();

            {... I Populate the roles here ...}

            DataContractJsonSerializer serializer = new
            DataContractJsonSerializer(roles.GetType());
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, roles);
            string jsonString = Encoding.Default.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }
Run Code Online (Sandbox Code Playgroud)

这正确地正确地格式化List,但是用XML包装整个返回.以下是回复:

<?xml version="1.0" encoding="utf-8" ?> 
    <string xmlns="http://formshare.com/">
       [{"Name":"Accounts Payable"},{"Name":"Payroll"}]
    </string>
Run Code Online (Sandbox Code Playgroud)

您可以通过单击此链接查看自己的响应:

http://dev.formshare.gologictech.com/JSON/JSONService.asmx/GetUserRoles?JSONUserCode=1234

我需要的回应是:

[{"Name":"Accounts Payable"},{"Name":"Payroll"}]
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢你的帮助.

Dav*_*und 12

WebMethod能够提供与XML和JSON相同的信息.在提交请求时,您需要在客户端中指定所需的格式(dataType).

此外,您不应该手动将对象序列化为JSON,而是返回角色,如果您的客户端请求数据为JSON,它将被序列化为JSON.

编辑

jQuery示例(注意dataType参数):

$.ajax({
   type: 'GET',
   url: 'http://dev.formshare.gologictech.com/JSON/JSONService.asmx/GetUserRoles',
   contentType: 'application/json; charset=utf-8',
   dataType: 'json',
   data: '{"JSONUserCode":"1234"}',
   success: myCallback
});
Run Code Online (Sandbox Code Playgroud)

值得一提的是,对象不会以您指定的格式返回,而是包装在对象中:

{ d: [ {"Name":"Accounts Payable"}, {"Name":"Payroll"} ] }
Run Code Online (Sandbox Code Playgroud)

然而,这实际上是非常理想的,以增加安全性