在尝试使用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问题。
我不能使用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);
}
})
该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}}}'