ASP.NET JSON Web服务始终返回以XML包装的JSON响应 [英] ASP.NET JSON web service always return the JSON response wrapped in XML

查看:133
本文介绍了ASP.NET JSON Web服务始终返回以XML包装的JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I saw a similar question but it did not resolve my issue. I have a JSON web service in an ASMX file;

网络方法的代码

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

这样可以正确设置列表的格式,但是将整个返回结果包装为XML.这是响应:

This correctly formats the List correctly but wraps the entire return in XML. Here is the response:

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

您可以通过单击以下链接查看自己的回复:

You can view the Response your self by clicking this link:

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

我需要的答复是:

[{"Name":"Accounts Payable"},{"Name":"Payroll"}]

有什么想法吗?感谢您的帮助.

Any ideas? Thanks for your help.

推荐答案

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

The WebMethod is able to serve the same information both as XML and JSON. You need to specify what format you want (dataType) in the client, as you submit your request.

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

Also, you're not supposed to serialize the object to JSON manually, but rather, return roles, and it will be serialized to JSON if your client requests the data as JSON.

编辑

jQuery示例(请注意dataType参数):

jQuery example (note the dataType parameter):

$.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
});

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

It is worth mentioning that the object will not be returned in exactly the format you specified, but rather, wrapped in an object:

{ d: [ {"Name":"Accounts Payable"}, {"Name":"Payroll"} ] }

但是,实际上这是非常可取的,以提高安全性

This, however, is actually quite desirable, for added security

这篇关于ASP.NET JSON Web服务始终返回以XML包装的JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆