在尝试在 javascript 中手动格式化我的 JSON 数据并惨遭失败后,我意识到可能有更好的方法。下面是 Web 服务方法和相关类的代码在 C# 中的样子:
[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;
}
Web 服务在使用 SOAP/XML 时效果很好,但我似乎无法使用 javascript 和 jQuery 获得有效响应,因为我从服务器返回的消息与我的手动编码 JSON 有问题。
我无法使用 jQuerygetJSON
函数,因为请求需要 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);
}
})
该ajax
函数正在提交 中指定的所有内容data:
,这就是我的问题所在。如何在 javascript 中构建格式正确的 JSON 对象,以便我可以将其插入到我的ajax
调用中,如下所示:
data: theRequest
我最终会从表单中的文本输入中提取数据,但现在硬编码的测试数据很好。
如何构建格式正确的 JSON 对象以发送到 Web 服务?
更新:事实证明,正如 TJ 指出的那样,我的请求的问题不是 JSON 的格式,而是我的 JSON 文本不符合 Web 服务的要求。这是基于 WebMethod 中的代码的有效 JSON 请求:
'{"request":{"Address":{"Address1":"123 Main Street","Address2":"suite 20","City":"New York","State":"NY","Zip":"10000","AddressClassification":null}}}'