Serializing your javascript objects or collections to valid json to submit with an ajax-enabled WCF service

Recently, one of the things I found myself struggling a bit with, was submitting my javascript object collection to an ajax-enabled WCF service which was expecting a object or object collection of a certain type. At first I kept getting format errors because my self created JSON object collection was not formatted correctly and thus the object collection could not be parsed correctly by our ajax WCF service.

Suppose we have a very simple data contract:

Serializing javascript object collection to valid json for ajax WCF service

We have an AJAX-enabled WCF service, that has a method that accepts an ienumerable of our data contract:

Serializing javascript object collection to JSON for AJAX enabled WCF service

We can build our object in javascript with the available properties and serialize the array with JSON.stringify:

Serializing javascript objects to JSON with JSON.Stringify

The result of JSON.stringify on the javascript object array will be a JSON parsed collection of employee:

{“employees”:[{"Firstname":"Robbin","Lastname":"Cremers","Email":"robbin.cremers@email.be"},{"Firstname":"Scott","Lastname":"Guthrie","Email":"scrott.guthrie@microsoft.com"}]}

The other solution is to write your objects in the JSON format immediately, but that is not any fun thing to do. When you are starting to build complex collection with multiple object levels, writing the json format manually is almost impossible. JSON.stringify just does the work for you!

Cheers,
Robbin

About these ads

2 comments on “Serializing your javascript objects or collections to valid json to submit with an ajax-enabled WCF service

  1. Hi Robbin,
    I am hoping you can point out my mistake. I have stumpled upon your website after researching passing arrays in javascript. To my Surprise, I didn’t have to change much to get my code looking like your example. No matter what I try I cannot get to the method to hit a break point inside the WCF method. I only get a 500 internal error response in the result object of the onError handler. Any advice would be appreciated, as I have resulted to falling back to a string array and parsing out the values in the service method.

    *** WCF METHOD***

    public string Test(IEnumerable i)
    {
    string msg = “Success!\n”;
    foreach (_SystemGridUserProfile s in i)
    {
    //msg += s.GridOrdinal + ‘\n';
    //msg += s.GridWidth + ‘\n';
    msg += s.SystemGridUserProfileID + ‘\n';
    msg += s.GridProfileName + ‘\n';
    msg += s.SystemGridID + ‘\n';
    }
    return msg;
    }

    *** DATA CONTRACT***

    [DataContract]
    public class _SystemGridUser
    {
    [DataMember]
    public long SystemGridUserID;

    [DataMember]
    public long SystemGridUserProfileID;

    [DataMember]
    public long SystemGridFieldID;

    [DataMember]
    public int GridOrdinal;

    [DataMember]
    public int GridWidth;
    }

    *** JAVASCRIPT **

    function insertGridCus(sender, args) {
    //create objects to pass to service
    var users = new Array();

    //get columns
    var columns = $find(“”).get_masterTableView().get_columns();

    var i;
    for (i = 1; i < columns.length; i++)//starting at one skips the expand column
    {
    var user = new Object();

    user.GridOrdinal = i;
    user.GridWidth = columns[i].get_element().clientWidth;
    user.SystemGridFieldID = columns[i].get_uniqueName();

    users.push(user);
    }

    var data = { i: users };

    $.ajax({
    type: "POST",
    url: "/iTracker.Web/Service/Web.svc/Test",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(data),
    dataType: "json",
    success: testSuccess,
    error: onError
    });

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s