How can I build a JSON array in webcore.
I want to build this
[{"question_number":"1","survey_id":"776BE7A5-1FBF-477F-B059-431001A70395","response":"Mild"},{"question_number":"2","survey_id":"776BE7A5-1FBF-477F-B059-431001A70395","response":"None"}]
In VCL I could add pairs to the JSONObject and then add the objects to a JSONArray using
JSONArray.Add(JSONObject);
But there is no "Add" method for JSONArray in webcore.
I am also unable to figure out proper use of JSONObject and JSONArray. Have literally spent days and making no progress. It is not clear to me if I just know too little about marrying the Pascal and JavaScript worlds, or if there is still functionality lacking in Web Core. I am very interested to see a reply to your post that shows the proper way.
My current solution (that works well for my purposes) is to not use the WEBLib,JSON unit, but instead use the JS external interface. It allows me to compose Pascal records and arrays, and then marshal them to JSON strings.
Here is a sample console app to marshal your data to JSON:
program SamplePascalToJson;
{$APPTYPE CONSOLE}
{$R *.res}
uses
browserconsole, JS;
type
// Explicitly define the record type because Pas2JS does not yet support anonymous records
TQuestion = Record
question_number: Integer;
survey_id: String;
response: String;
end;
// The array type
TQuestions = Array of TQuestion;
var
Questions: TQuestions;
JsonString: String;
begin
// Populate the Pascal array of record
SetLength(Questions, 2);
With Questions[0] do
begin
question_number := 1;
survey_id := '776BE7A5-1FBF-477F-B059-431001A70395';
response := 'Mild';
end;
With Questions[1] do
begin
question_number := 2;
survey_id := '776BE7A5-1FBF-477F-B059-431001A70395';
response := 'None';
end;
// Marshall the Pascal array to JSON
// Use the external JS interface
JsonString := TJSJSON.stringify(Questions);
Writeln('And the JSON is... ' + JsonString);
end.
Hi,
Maybe this examle will be helpful:
function TDansoftWEBService.getWebServiceLog: TJSONArray;
var Writer: TJSONTextWriter;
StringWriter: TStringWriter;
i:Integer;
logFile:TStringList;
begin
try
StringWriter:= TStringWriter.Create();
Writer := TJSONTextWriter.Create(StringWriter);
logFile:=TStringList.Create;
try
Writer.WriteStartArray;
for i:=0 to logFile.Count-1 do
begin
Writer.WriteStartObject;
Writer.WritePropertyName('Line');
Writer.WriteValue(logFile
);
Writer.WriteEndObject;
end;
Writer.WriteEndArray;
Result := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(StringWriter.ToString),0) as TJSONArray;
finally
FreeAndNil(Writer);
FreeAndNil(StringWriter);
FreeAndNil(logFile);
end;
except
on e: System.SysUtils.Exception do
begin
raise;
end;
end;
end;