How do I build a JSON object to send to an AJAX WebService?

Posted by Ben McCormack on Stack Overflow See other posts from Stack Overflow or by Ben McCormack
Published on 2010-04-29T13:10:08Z Indexed on 2010/04/29 13:17 UTC
Read the original article Hit count: 313

Filed under:
|
|
|
|

After trying to format my JSON data by hand in javascript and failing miserably, I realized there's probably a better way. Here's what the code for the web service method and relevant classes looks like in 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;
}

The web service works great with using SOAP/XML, but I can't seem to get a valid response using javascript and jQuery because the message I get back from the server has a problem with my hand-coded JSON.

I can't use the jQuery getJSON function because the request requires HTTP POST, so I'm using the lower-level ajax function instead:

$.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);
    }
})

The ajax function is submitting everything specified in data:, which is where my problem is. How do I build a properly formatted JSON object in javascript so I can plug it in to my ajax call like so:

data: theRequest

I'll eventually be pulling data out of text inputs in forms, but for now hard-coded test data is fine.

How do I build a properly formatted JSON object to send to the web service?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery