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:


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!


About these ads