简体   繁体   中英

Delphi - How do I create a TJSONArray from a array of strings?

I have the following array of strings :

001,002,005,009

And I need to create a TJSONArray from it:

["001","002","005","009"]

 JSONObj := TJSONObject.Create;
 JSONObj.AddPair(TJSONPair.Create('Events', (response_faults as TJSONArray)));

I've tried to create the object and pass the array of strings as a TJSONArray but I'm getting:

E2015 Operator not applicable to this operand type

How do I generate a TJSONArray from a array of strings ?

You need to construct an empty TJSONArray object first, and then Add() the individual strings values to it. For example:

var
  arr: array of string;
  JSONObj: TJSONObject;
  response_faults: TJSONArray;
  I: Integer;
begin
  arr := ... ; // '001', '002', '005', '009', ...
  JSONObj := TJSONObject.Create;
  try
    response_faults := TJSONArray.Create;
    try
      for I := Low(arr) to High(arr) do begin
        response_faults.Add(arr[I]);
      end;
      JSONObj.AddPair('Events', response_faults);
    except
      response_faults.Free;
      raise;
    end;
    // use JSONObj as needed...
  finally
    JSONObj.Free;
  end;
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM