if xxx.findfirst then begin json_string := '['; // array start repeat json_string := json_string + '{'; for index := 0 to xxx.fields.count -1 do begin json_string := json_string + '"' + xxx.fields[index].fieldName + '":"' + xxx.fields[index].asstring + '",'; // make sure that you take care of the comma above end; json_string := json_string + '},'; // again, comma! until NOT xxx.FindNext; json_string := json_string + ']'; array end end;
the above is a rough idea, you have to take care of each field type accordingly, i.e. integer and boolean: "some_int_field": 2014 <- note that we're not double quoting the "2014" value string: double quote, make sure to escape string properly
It is not just a matter of serializing a dataset to JSON, I tried to build a reversed version of what is done by TRestResponseDatasetAdapter (nested objects support included)... This means you can send back data to the server in the same JSON structure it gave data to the client.
Delphi version?
ReplyDeleteXE5 has usable JSON components, even if they are a tad slow and you have to do content sanitation yourself (escaping, etc).
ReplyDeleteXE6
ReplyDeleteLennart Aasenden
ReplyDeleteif xxx.findfirst then begin
ReplyDeletejson_string := '['; // array start
repeat
json_string := json_string + '{';
for index := 0 to xxx.fields.count -1 do begin
json_string := json_string + '"' + xxx.fields[index].fieldName + '":"' + xxx.fields[index].asstring + '",';
// make sure that you take care of the comma above
end;
json_string := json_string + '},';
// again, comma!
until NOT xxx.FindNext;
json_string := json_string + ']'; array end
end;
the above is a rough idea, you have to take care of each field type accordingly, i.e.
integer and boolean:
"some_int_field": 2014 <- note that we're not double quoting the "2014" value
string:
double quote, make sure to escape string properly
have fun!
XE6 - been manually doing it using XSuperObject, just wondered if there was a reverse of TRestResponseDatasetAdapter
ReplyDeleteYes there is, Andrea Magni published it
ReplyDeleteHi here is my blog post (in Italian, please use Google translate) : http://blog.delphiedintorni.it/2014/07/tdatasetrestrequestadapter-serializzare.html?m=1 Source code is available on my github account (there is a link in the blog post)... Thanks Andrea Raimondi
ReplyDeleteMany thanks Andrea
ReplyDeleteIn in case you havent heard of SMS, it's an object pascal compiler/IDE that compiles to JavaScript :)
ReplyDeleteThanks Lennart Aasenden. I have SMS on the list.
ReplyDeleteIt is not just a matter of serializing a dataset to JSON, I tried to build a reversed version of what is done by TRestResponseDatasetAdapter (nested objects support included)... This means you can send back data to the server in the same JSON structure it gave data to the client.
ReplyDelete