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

查看:31
本文介绍了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;

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

这正确地格式化了列表,但将整个返回包装在 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 相同的信息.在提交请求时,您需要在客户端指定您想要的格式 (dataType).

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天全站免登陆