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

Solution 1:

The answer is very easy and based on my previous posts Can I return JSON from an .asmx Web Service if the ContentType is not JSON? and JQuery ajax call to httpget webmethod (c#) not working.

The data should be JSON-encoded. You should separate encode every input parameter. Because you have only one parameter you should do like following:

first construct you data as native JavaScript data like:

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

then give as a parameter of ajax request {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);
    }
})

instead of $.toJSON which come from the JSON plugin you can use another version (JSON.stringify) from http://www.json.org/

If your WebMethod had parameters like

public Response ValidateAddress(Request request1, Request myRequest2)

the value of data parameter of the ajax call should be like

data: {request1:$.toJSON(myData1), myRequest2:$.toJSON(myData2)}

or

data: {request1:JSON.stringify(myData1), myRequest2:JSON.stringify(myData2)}

if you prefer another version of JSON encoder.

Solution 2:

Your problem breaks down into two parts:

Creating the JSON string

Your JSON in your quoted code is perfectly valid. But being hand-crafted is a pain. As others have called out, the easiest way to do this is to create a Javascript object and then JSON.stringify it. Example:

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

The first step above creates an object using Javascript object literal notation, which is a superset of JSON (as used above, it actually is the same as JSON, but ignore that). The second bit takes that object and converts it to a string.

Of course, the values above are literal strings, which is unlikely. Here's what it would look like if you had each of those values in a variable:

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

Either way, now you have the string.

Sending the JSON string to the web service

You need to find out is whether the web service is expecting the JSON-formatted data to be the POST body, or if it's expecting the JSON data to be the value of a parameter in the more common name=value URL-encoded POST data. I would tend to expect the former, because the web service seems specifically designed to work with JSON-formatted data.

If it's supposed to be the POST body, well, I've never done that with jQuery, and what you have quoted looks correct to me reading the docs. If it's not working, I'd double-check that your object structure is really what they're expecting to see. For instance, if it's just validating a single address, I wonder if it's expecting to receive just an Address object, rather than an object containing an Address object, e.g.:

{
    "Address1": "123 Main Street",
    "Address2": null,
    "City": "New York",
    "State": "NY",
    "Zip": "10000",
    "AddressClassification": null
}

If it's supposed to be the value of a parameter in boring old URL-encoded multipart form data, then:

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

I've removed the contentType so jQuery will fall back to its default ("application/x-www-form-urlencoded") and ensured the string we created above is properly encoded in that content type. You'll need to find out the paramname to use (perhaps "Address" and see my earlier comment about sending just the address, rather than an object containing an address child object?).

Solution 3:

JSON.stringify will take a javascript object and turn it into a string. I bet though that if you create a Javascript object like

var jsonData = {
    address: 'address',
    address1: 'address1',
    address2: 'address2'
};

and then pass in jsonData as 'data' in the ajax call, then it will convert the object to json text for you.

Solution 4:

I would create a javascript object and then call JSON.stringify to turn it into valid JSON. You can download it from here.

You could do something like this:

var address= {};

address["Address1"] = "your val";
address["Address2"] = "your val";
address["City"] = "your val";
address["State"] = "your val";
address["Zip"] = "your val";

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "http://bmccorm-xp/HBUpsAddressValidation/AddressValidation.asmx/ValidateAddress",
    data: JSON.stringify(address),
    dataType: "json",
    success: function(response){
        alert(response);
    }
});

Solution 5:

You need to pass it like this:

$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: "{'fname':'dave', 'lname':'ward'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});

Have a look at this article for more details: 3 mistakes to avoid when using jQuery with ASP.NET AJAX