This article demonstrates how to serialize Delphi type objects into JSON-encoded data and then deserialize data in the JSON format back into instances of Delphi types using the Json Serializer. The example includes both the source code of the Json Serializer class (TclJsonSerializer) and a unit-test code that demonstrates how to serialize and deserizlise differrent data types, inlcuding Delphi strings, integers, objects and arrays. TclJsonSerializer utilizes the RTTI library and custom Delphi attributes for linking user-defined Delphi objects and properties with the corresponding JSON data parts. The December's update provides separated classes for the abstract JSON structures and parser implementation. This helps users to change the program so that it does the same job without the non-free library -.
Minor fixes and improvements were included as well. Define a data type For defining a data type, you need to attach the TclJsonPropertyAttribute attribute to the property you want to serialize. // [Delphi] TclTestObject = class private FStringValue: string; FIntegerValue: Integer; FIntArray: TArray; public [TclJsonString('stringValue')] property StringValue: string read FStringValue write FStringValue; [TclJsonProperty('integerValue')] property IntegerValue: Integer read FIntegerValue write FIntegerValue; [TclJsonProperty('intArray')] property IntArray: TArray read FIntArray write FIntArray; end; Serialize an instance of data type to JSON 1. Create an instance of data type.
// [Delphi] obj:= TclTestObject.Create(); obj.StringValue:= 'test'; obj.IntegerValue:= 123; SetLength(intArr, 2); obj.IntArray:= intArr; intArr:= 111; intArr:= 222; 2. Serialize the object to the JSON string. // [Delphi] json:= TclJsonSerializer.ObjectToJson(obj); Deserialize an instance of data type from JSON Call to the TclJsonSerializer.JsonToObject class method and specify both the serializeble data type and the JSON-encoded source string. // [Delphi] obj:= TclJsonSerializer.JsonToObject(TclTestObject, jsonEtalon) as TclTestObject; Supported compiler versions Json Serializer can be used in RAD Studio XE3 and later.
If you modify the sources and remove all references to the RAD Studio namespaces in the 'uses' sections, you can use the library in RAD Studio 2009, 2010, XE and XE2 as well. Download source code Old version Download The library is distributed under the terms of the, Sergey Shirokov Clever Components team.