RAD Studio has offered support for JSON in different ways and for a long time. From the JSON system unit (originally part of the DBX space) to the old DataSnap table mapping (also via DBX) and to FireDAC tables to JSON mapping, there are many ways to interact with JSON data structures. However, until the most recent release, we lacked a way to map a dataset to a custom JSON structure -- the FireDAC JSON support produces a FireDAC specific structure, with meta data and record status information.
I'll describe the solution using two demos. The first is a plain VCL application. while the second will be a RAD Server package. This highlights the fact that the solution is fairly general. In the first demo, I have the following components on a form (I know, I should have used a data module...):
This is the configuration of the components:
With this configuration in place, all you need to do to produce the JSON is connect the output to the JSON writer and execute the batch move operation. In this case I've used a stream:
Other options are assigning to the writer for the output a JSONWriter (as I'll show shortly) or a JSONArray.
For the second demo, the RAD Server demo, I've used the same set of components with the same configuration. In this cases I've added to an EMS package an "employee" resource, and implemented its get operation with the following stream-based code:
As a better and simpler alternative, I could have used the JSONWriter property. The difference is that rather tha building the entire JSON data structure in the memory stream and later copy it to the HTML response, the data is written directly to the HTML response, reducing the work and the memory consumption:
In both cases, you'll see an output like the following: