Is there a way to convert this Record
TError = record
code: Word;
message: String;
end;
TState = record
caption: String;
address: Cardinal;
counters: TArray<Word>;
errors: TArray<TError>;
end;
to serialized Form Data string (Content-Type: application/x-www-form-urlencoded) like
caption=Foo&
address=175896&
counters[]=2&
counters[]=2&
errors[0][code]=52&
errors[0][message]=ERR_NOT_AVAILABLE
for sending via HTTP?
Maybe there is some function similar to JQuery.param()?
Ok, here is a boilerplate solution which can be adapted for your specific serialization or other use as well.
A record,
TSerializer, does all the serialization job and the result is stored in a string list.To use it, call method
Serialize('state', TValue.From(state),sList);from aTSerializerinstance.You can add most types that fit into a
TValue, including records, static arrays, dynamic arrays and simple classes. The unwinding of all elements are made by recursion.(Disclaimer, this is tested on XE2, but I think Delphi-2010 supports all enhanced-RTTI calls used here)
The output from your example looks like this:
Here is the source unit:
And a test unit:
I had a little help studying Barry Kellys answer to the question Rtti accessing fields and properties in complex data structures.