[英]Parse an array of strings in JSON
In Delphi 10 Seattle, I am trying to parse a JSON that contains an array of strings in a property.在 Delphi 10 Seattle 中,我试图解析一个 JSON,其中包含属性中的字符串数组。
As an example, consider this:例如,考虑一下:
{
"name":"Joe",
"age":45,
"languages":["c++", "java", "cobol"]
}
How do I parse languages
to obtain an array of strings?如何解析
languages
以获取字符串数组?
function TForm1.GetLangArray(const AJSONStr: String): TArray<String>;
var
AJSONVal, AJSONElem: TJSONValue;
AJSONArray: TJSONArray;
i: Integer;
begin
AJSONVal := TJSONObject.ParseJSONValue(AJSONStr);
AJSONVal := AJSONVal.P['languages'];
if (AJSONVal is TJSONArray) then
AJSONArray := AJSONVal as TJSONArray
else
Exit;
with AJSONArray do
begin
SetLength(Result, Count);
i := 0;
for AJSONElem in AJSONArray do
begin
Result[i] := AJSONelem.Value;
Inc(i);
end;
end;
end;
Try something like this:尝试这样的事情:
function GetLanguagesArray(const AJSON: String): TArray<String>;
var
LValue: TJSONValue;
LArray: TJSONArray;
i: Integer;
begin
Result := nil;
LValue := TJSONObject.ParseJSONValue(AJSON);
if LValue <> nil then
try
LArray := (LValue as TJSONObject).GetValue('languages') as TJSONArray;
SetLength(Result, LArray.Count);
for i := 0 to Pred(LArray.Count) do
begin
Result[i] := LArray[i].Value;
end;
finally
LValue.Free;
end;
end;
Very easy with REST.JSON, using helper to parse and read array items使用 REST.JSON 非常容易,使用帮助器解析和读取数组项
type
TDeveloper = class
private
FAge : Integer;
FName : string;
FLanguages: TArray<string>;
public
property Age : Integer read FAge write FAge;
property Name : string read FName write FName;
property Languages: TArray<string> read FLanguages write FLanguages;
end;
// Sample
var
FDeveloper: TDeveloper;
FLanguage : string;
begin
try
FDeveloper := TJson.JsonToObject<TDeveloper>(Memo1.Text);
Memo2.Clear;
Memo2.Lines.Add('------------------------------ ');
Memo2.Lines.Add('Name: ' + FDeveloper.Name);
Memo2.Lines.Add('Age : ' + FDeveloper.Age.ToString);
for FLanguage in FDeveloper.Languages do
begin
Memo2.Lines.Add('------------------------------ ');
Memo2.Lines.Add(FLanguage);
end;
finally
FreeAndNil(FDeveloper);
end;
See image: [1]: https://i.stack.imgur.com/69Zao.png参见图片:[1]: https://i.stack.imgur.com/69Zao.png
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.