Webservice – Return Generic Result Type or Purposed Result Type

asp.net-mvccjavascriptmicrosoft

I'm building a webservice which returns JSON / XML / SOAP at the moment.. and I'm not entirely sure which approach for returning results is best.

The Client Consuming the Services will generally be Web Applications / Mobile Web Applications. But could be from various WordPress and other social media Plugin type systems.

Which would be a better return value?

A generic "transfer" type structure, which carries Generic properties or a purposed type with distinct properties:

class GenericTransferObject{
    public string returnVal;
    public string returnType;
}

VS

class PurposedTransferObject_1{
  public string Property1;
}

//and then building additional "types" for additional values
class PurposedTransferObject_2 {
  public string PropertyA;
  public string PropertyB;
}

Now, this would be the serialized and returned from a web service call via some client technology, JQuery in this example. SO if I called:

/GetDaysInWeek/

I would either get back:

{"returnType": "DaysInWeek",
"returnVal": "365"
}

OR

{"DaysInWeek": "365"}

And then it would go from there.

On the one hand there's flexibilty with the 1st example. I can add "returnTypes" without needing to adjust the client other than referencing an additional "index"..

but if I had to add a property, now i'm changing a structure definition..

Is there an obvious choice in this situation?

Best Answer

I would think for the most part you would be better off with the distinct and typed properties in the for-purpose objects for several reasons:

  1. It makes it easier for some clients to consume your entities. For example there are JSON and XML parsers that will automatically create the representations of your objects from existing tools. It puts more of a burden on that side with the more generic non-standard representation (similar to the problem with EAV in SQL databases).
  2. Consuming clients may be less trusting of the implied contract of the API to deliver non-breaking changes with the looser representations and it would be easy to accidentally create breaking changes that are hard to troubleshoot.
  3. It will be more difficult to represent other data value types if everything is a string. You would have to add another property called "returnValuetype" and then it starts getting overly messy as you will have to check that in your parser as well. There are enough problems with date-time representations already.