Thursday, 27 July 2017

JSON RTTI Mapper with Delphi

One of the patterns that I have observed a lot during the time I have been playing with JSON streams is that I create my object based on the JSON stream and then I set the properties of that particular object manually so I can work with it rather than with the JSON object itself. 

Let's observe the following example. Imagine that we have the following JSON stream:


As you can see this JSON represents a list of Employees and each employee has the properties Name, Surname, Age and Address. So if we want to hold this in a TList<T> then we will have to create a class TEmployee with those properties and then manually assign each JSON parameter to each property like the example below:

The code is quite straight forward. We need to loop through the JSON array and populate the list.

If you look closely, you will see that basically we are mapping a field in the JSON object that it's called "name" to an object property called "Name". So to make it simpler this would literally be something like this:

Any mapper out there does one simple job and it's the job of mapping one field from one source to another.

So the question here is how to achieve this in a more clever way? Easy, let's use RTTI to map those properties!

Using the methods TypInfo.SetStrProp and TypInfo.GetPropList you can easily explore and the list of published properties of your class and set the value of them. To make use of the RTTI capabilities, you will have to move those properties to the published section of the class so they are visible through the RTTI.

Now you know how to use the RTTI to read the list of published properties and set them to a specific value. These examples have been coded with Delphi 10.2 Tokyo and you can find part of the mapper in one of the projects I'm currently working on: COCAnalytics.

There are many libraries out there that do amazing things with JSON so it's up to you to explore them. At least now you know how to map using the RTTI.

Happy coding!.

Jordi
Delphi MVP.

0 comments:

Post a Comment