MARS-Curiosity: new feature! Automatic deserialization (MessageBodyReader)
I’ve added a new feature to MARS-Curiosity library: automatic deserialization of http body content!
With a natural symmetry with respect to MessageBodyWriter (serialization of the result value of a method into the http response), there is now a MessageBodyReader mechanism and a registry that holds a list of readers ready to be used when needed.
The first MessageBodyReader implemented is the TJSONValueReader (MARS.Core.MessageBodyReaders unit) and will let you easily receive JSON values with automatic deserialization (passing from the JSON string received into the http request body to an actual TJSONObject or TJSONArray instance).
Just imagine you want to handle an http POST request and the client should send a (JSON) array of elements to the server. Your MARS-Curiosity method now can be like this:
[POST, Path('/countitems')]
function CountItems([BodyParam] Data: TJSONArray): Integer;
(...)
function THelloWorldResource.CountItems(Data: TJSONArray): Integer;
begin
Result := Data.Count;
end;
Here is a screenshot of a sample request (using Postman client):
Obviously, the MessageBodyReader mechanism is implemented using a registry that will select the proper reader according to the content of the MessageBodyReader registry and the Delphi data type of the argument of the method (properly decorated with the BodyParam attribute).
For example, if you are using an ORM, it would be nice to add a MessageBodyReader / MessageBodyWriter couple to serialize your objects into JSON strings and deserialize their JSON string representation back to Delphi instances. Just to have an idea of the effort, have a look at the MessageBodyWriter implementation for TJSONValue (MARS.Core.MessageBodyWriters unit) and to the MessageBodyReader implementation (MARS.Core.MessageBodyReaders unit) where you can find (respectively) the TJSONValueWriter and TJSONValueReader classes.
Enjoy and feel free to let me know your opinion/thoughts.
I will showcase MARS-Curiosity library in some upcoming conferences, there is a Google+ community and also a YouTube playlist with some entries for this project.
Stay tuned on this blog, other news will follow 😉
Andrea