abraganza
abraganza

Reputation: 135

Is there an ODataSerializer to serial custom objects?

I need something to take an arbitrary Object/List/Dictionary returned to me by a call to a WCF Service to be serialized to OData. I am currently using the WCF Data Services October 2011 CTP to accomplish this, generating the ODataEntry/ODataFeed etc, using reflection, but if there is already something implemented I'd rather use that instead of reinventing the wheel...

Any help / information would be greatly appreciated.

For example:

Person p = new Person()
{
PersonID = 1,
FirstName = "Bob",
LastName = "Smith",
Address = new Address()
     {
          AddressID = 1,
          Address1 = "1 Main St",
          Address2 = "Suite 200",
          City = "Columbus",
          State = "OH",
          ZipCode = "43215"
     }
};

would translate to

{
  "d":{
    "__metadata":{
      "id":"Person(1)","uri":"http://serviceroot/Person(1)","type":"MyProject.Person"
    },
"PersonID":1,
"FirstName":"Bob",
"LastName":"Smith",
"Address":{
              "AddressID":1,
              "Address1":"1 Main St",
              "Address2":"Suite 200",
              "City":"Columbus",
              "State":"OH",
              "ZipCode":"43215"
          }
      }
}

Upvotes: 3

Views: 666

Answers (1)

keenthinker
keenthinker

Reputation: 7830

Since the OData format is JSON, i would suggest using ServiceStack.Text. It is a fast .NET serializer written exactly for such purposes. It is part of the ServiceStack web services framework and the usage is really simple.

1) Import and reference ServiceStack framework in your project (either via NuGet or directly from GitHub)

2) Create and fill the complex object as you already do:

Person p = new Person()
{
    PersonId = 1,
    FirstName = "Bob",
    LastName = "Smith",
    Address = new Address()
    {
        AddressId = 1,
        Address1 = "1 Main St",
        Address2 = "Suite 200",
        City = "Columbus",
        State = "OH",
        ZipCode = "43215"
    }
};

3) Call the ToJson extension method from the complex object:

p.ToJson();

4) Voila - the output (as desired):

{
  "PersonId": 1,
  "FirstName": "Bob",
  "LastName": "Smith",
  "Address": 
  {
    "AddressId": 1,
    "Address1": "1 Main St",
    "Address2": "Suite 200",
    "City": "Columbus",
    "State": "OH",
    "ZipCode": "43215"
  }
}

Hint: In order to print the output for debug purposes use PrintDump():

p.ToJson().PrintDump(); 

Upvotes: 1

Related Questions