locked
WCF - Accept JSON Collection RRS feed

  • Question

  • Hello,

    I am writing a WCF Service operation that needs to take in a collection of JSON objects. For instance, a sample collection looks like the following in JavaScript:

     

    var entries = {
     coll : [
      { "firstName":"John", "age":27 },
      { "firstName":"Peter", "age":30 },
      { "firstName":"Bill", "age":48 }
     ]
    };
    

     

    This collection is dynamically constructed via JavaScript on the client-side. Because of this, there could be many more entries. Currently, I have a WCF operation setup like the following:

    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    public bool SaveEntries(/* some parameters */)
    {
     // Parse the entries
    }
    

    This operation is being called from my JavaScript as follows:

    var json = { };
    $.ajax({
     type: "POST",
     url: "/resources/myService.svc/SaveEntries",
     contentType: "application/json; charset=utf-8",
     data: json,
     dataType: "json",
     success: saveCompleted,
     error: saveFailed
    });
    

    I know how to execute the service for a single object. To accomplish that, I would just pass along the object properties as parameters and have the corresponding parameters on the operation. But that approach is not scalable for more than one object.

    How do I pass a JSON collection to a WCF operation and parse it?

    Thank you!

    Wednesday, June 9, 2010 1:36 PM