如何构建要发送到AJAX WebService的JSON对象?

Ben*_*ack 15 javascript c# jquery json web-services

在尝试使用javascript手动格式化我的JSON数据并且失败后,我意识到可能有更好的方法.以下是C#中Web服务方法和相关类的代码:

[WebMethod]
public Response ValidateAddress(Request request)
{
    return new test_AddressValidation().GenerateResponse(
        test_AddressValidation.ResponseType.Ambiguous);
}

...

public class Request
{
    public Address Address;
}

public class Address
{
    public string Address1;
    public string Address2;
    public string City;
    public string State;
    public string Zip;
    public AddressClassification AddressClassification;
}

public class AddressClassification
{
    public int Code;
    public string Description;
}
Run Code Online (Sandbox Code Playgroud)

Web服务使用SOAP/XML很有效,但我似乎无法使用javascript和jQuery获得有效的响应,因为我从服务器返回的消息与我的手工编码的JSON有问题.

我不能使用jQuery getJSON函数,因为请求需要HTTP POST,所以我使用的是低级ajax函数:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "http://bmccorm-xp/HBUpsAddressValidation/AddressValidation.asmx/ValidateAddress",
    data: "{\"Address\":{\"Address1\":\"123 Main Street\",\"Address2\":null,\"City\":\"New York\",\"State\":\"NY\",\"Zip\":\"10000\",\"AddressClassification\":null}}",
    dataType: "json",
    success: function(response){
        alert(response);
    }
})
Run Code Online (Sandbox Code Playgroud)

ajax函数正在提交指定的所有内容data:,这就是我的问题所在.如何在javascript中构建格式正确的JSON对象,以便我可以将其插入到我的ajax调用中,如下所示:

data: theRequest
Run Code Online (Sandbox Code Playgroud)

我最终会从表单中的文本输入中提取数据,但是现在硬编码的测试数据很好.

如何构建格式正确的JSON对象以发送到Web服务?


更新:事实证明,我的请求的问题不是JSON的格式化,正如TJ指出的那样,而是我的JSON文本不符合Web服务的要求.这是基于WebMethod中的代码的有效JSON请求:

'{"request":{"Address":{"Address1":"123 Main Street","Address2":"suite 20","City":"New York","State":"NY","Zip":"10000","AddressClassification":null}}}'
Run Code Online (Sandbox Code Playgroud)

这提出了另一个问题:在对ASP.NET Web服务(ASMX)的JSON请求中,何时区分大小写很重要?

Ole*_*leg 12

答案很简单,基于我以前的帖子如果ContentType不是JSON,我可以从.asmx Web服务返回JSON吗?JQuery ajax调用httpget webmethod(c#)无法正常工作.

数据应该是JSON编码的.您应该为每个输入参数分别编码.因为您只有一个参数,您应该执行以下操作:

首先将数据构建为本机JavaScript数据,如:

var myData = {Address: {Address1:"address data 1",
                        Address2:"address data 2",
                        City: "Bonn",
                        State: "NRW",
                        Zip: "53353",
                        {Code: 123,
                         Description: "bla bla"}}};
Run Code Online (Sandbox Code Playgroud)

然后给出ajax请求的参数 {request:$.toJSON(myData)}

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "http://bmccorm-xp/HBUpsAddressValidation/AddressValidation.asmx/ValidateAddress",
    data: {request:$.toJSON(myData)},
    dataType: "json",
    success: function(response){
        alert(response);
    }
})
Run Code Online (Sandbox Code Playgroud)

而不是来自JSON插件的$ .toJSON,你可以使用来自http://www.json.org/的另一个版本(JSON.stringify)

如果你的WebMethod有像这样的参数

public Response ValidateAddress(Request request1, Request myRequest2)
Run Code Online (Sandbox Code Playgroud)

调用data参数的值ajax应该是这样的

data: {request1:$.toJSON(myData1), myRequest2:$.toJSON(myData2)}
Run Code Online (Sandbox Code Playgroud)

要么

data: {request1:JSON.stringify(myData1), myRequest2:JSON.stringify(myData2)}
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢其他版本的JSON编码器.


T.J*_*der 5

您的问题分为两部分:

创建JSON字符串

引号中的JSON完全有效.但手工制作是一种痛苦.正如其他人所说,最简单的方法是创建一个Javascript对象,然后再创建JSON.stringify它.例:

var data = {
    "Address": {
        "Address1": "123 Main Street",
        "Address2": null,
        "City": "New York",
        "State": "NY",
        "Zip": "10000",
        "AddressClassification": null
    }
};
data = JSON.stringify(data);
Run Code Online (Sandbox Code Playgroud)

上面的第一步使用Javascript对象文字表示法创建一个对象,它是JSON的超集(如上所述,它实际上与JSON相同,但忽略它).第二个位接受该对象并将其转换为字符串.

当然,上面的值是文字字符串,这是不太可能的.如果您在变量中包含每个值,那么这就是它的样子:

var data = {
    "Address": {
        "Address1": address1,
        "Address2": address2,
        "City": city,
        "State": state,
        "Zip": zip,
        "AddressClassification": null
    }
};
data = JSON.stringify(data);
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,现在你有了字符串.

将JSON字符串发送到Web服务

您需要了解Web服务是否期望JSON格式的数据 POST主体,或者是否期望JSON数据是更常见的name = value URL编码的POST数据中的参数值.我倾向于期望前者,因为Web服务似乎专门设计用于处理JSON格式的数据.

如果它应该 POST主体,那么,我从来没有用jQuery做过,你所引用的内容看起来对我来说正确阅读文档.如果它不起作用,我会仔细检查你的对象结构是否真的是他们期望看到的.举例来说,如果它只是验证一个地址,我不知道它是否能接收只是一个Address对象,而不是包含一个Address对象,例如对象:

{
    "Address1": "123 Main Street",
    "Address2": null,
    "City": "New York",
    "State": "NY",
    "Zip": "10000",
    "AddressClassification": null
}
Run Code Online (Sandbox Code Playgroud)

如果它应该是无聊的旧URL编码的多部分表单数据中的参数值,那么:

$.ajax({
    type: "POST",
    url: "http://bmccorm-xp/HBUpsAddressValidation/AddressValidation.asmx/ValidateAddress",
    data: "paramname=" + encodeURIComponent(data),
    dataType: "json",
    success: function(response){
        alert(response);
    }
})
Run Code Online (Sandbox Code Playgroud)

我删除了contentType所以jQuery将回退到它的默认值("application/x-www-form-urlencoded")并确保我们在上面创建的字符串在该内容类型中正确编码.您需要找出paramname要使用的(可能是"地址"并查看我之前关于仅发送地址的注释,而不是包含地址子对象的对象?).