Web 服务应该返回 json [英] web service should return json

查看:39
本文介绍了Web 服务应该返回 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的网络服务返回 JSON...

I need my web service to return JSON...

我的 .asmx 文件中有以下代码:

I have the following code in my .asmx file:

namespace Feed
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    [System.Web.Script.Services.ScriptService]
    public class searchPerson : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public Person GetDave()
            {
                Person dave = new Person();

                dave.FirstName = "Dave";
                dave.LastName = "Ward";

         return dave;
        }
    }
}

返回以下内容:

<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
  <FirstName>Dave</FirstName>
  <LastName>Ward</LastName>
</Person>

如何强制它返回 JSON 而不是 XML?

How do I force it to return JSON instead of XML?

推荐答案

您的网络服务定义看起来正确.确保您通过帖子调用服务,并记住关键是将内容类型"标头指定为 application/json.

Your webservice definition looks correct. Ensure that you are calling the service through a post and remember that the key is specifying the 'content type' header as application/json.

(这是使用 jQuery,但如果您愿意,也可以使用低级 javascript)

(This is using jQuery but you could use low level javascript if you like)

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8;",
    url: "http://MyWebServiceURL",
    data: JSON.stringify({ ParameterName: "DataToSend" }),
    dataType: "json",
    success: function (data, textStatus, jqXHR) {
        //do something
    },
    error: function (jqXHR, textStatus, errorThrown) {
        //fail nicely
    }
});

这篇关于Web 服务应该返回 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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