Serializing objects to JSON and back using RTTI
When you are using a domain model pattern (and you should do most of the time for non-trivial applications), the entities managed by your program are contained in objects. An object has a state and methods to change its state, just like any actual object in the real world.
Getting ready
Just like the datasets in the previous recipe, the need to serialize an object in a JSON object, send the object somewhere, and then recreate that object as it was before is very common. In this recipe, we'll use the TJson class and extend it with new functionalities.
How to do it...
Perform the following steps:
- Create a new VCL Forms Application.
- Drop four TButtonand aTMemoon the form. Organize theTButtonin a single row as a sort of toolbar and align theTMemoto cover the remaining part of the form.
- Name the TButtoncomponents as follows:- btnObjToJSON
- btnJSONtoObject
- btnListToJSONArray
- btnJSONArrayToList
 
- Add a new unit to the project, name it JSON.Serializer.pas...
 
                                             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
     
         
                 
                 
                 
                 
                 
                 
        