在 Delphi 10 Seattle 中,我試圖決議一個 JSON,該 JSON 包含一個屬性中的字串陣列。
例如,考慮一下:
{
"name":"Joe",
"age":45,
"languages":["c ", "java", "cobol"]
}
如何決議languages以獲取字串陣列?
uj5u.com熱心網友回復:
嘗試這樣的事情:
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;
uj5u.com熱心網友回復:
使用 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;
見圖片:[1]:https : //i.stack.imgur.com/69Zao.png
uj5u.com熱心網友回復:
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;
更新
感謝@RemyLebeau 的評論。我修復了之前代碼的記憶體泄漏:
function TForm1.GetLangArray(const AJSONStr: String): TArray<String>;
var
AJSONVal, AJSONElem: TJSONValue;
AJSONArray: TJSONArray;
i: Integer;
begin
AJSONVal := TJSONObject.ParseJSONValue(AJSONStr);
try
AJSONArray := AJSONVal.P['languages'] as TJSONArray;
with AJSONArray do
begin
SetLength(Result, Count);
i := 0;
for AJSONElem in AJSONArray do
begin
Result[i] := AJSONElem.Value;
Inc(i);
end;
end;
finally
AJSONVal.Free;
end;
end;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/406494.html
標籤:
