[英]How to get the subitem value from a TRESTReponse in Delphi?
我需要獲取包含以下 JSON 的LResponse
的subitem1
值:
"Information": {
"subitem1": "2011",
"subitem2": "Test"
}
我正在使用此代碼獲取其他值,它運行良好,但是當我嘗試獲取Information
、 subitem1
或subitem2
,它返回一個空值。
var
LClient: TRESTClient;
LRequest: TRESTRequest;
LResponse: TRESTResponse;
begin
LClient := TRESTClient.Create(URL_API);
try
LRequest := TRESTRequest.Create(LClient);
try
LResponse := TRESTResponse.Create(LClient);
try
LRequest.Client := LClient;
LRequest.Response := LResponse;
LRequest.Method := rmGET;
LRequest.Params.AddHeader('Authorization','Bearer '+FToken);
LRequest.Params.ParameterByName('Authorization').Options := [poDoNotEncode];
LRequest.Params.AddHeader('Accept', 'application/json');
LRequest.Execute;
LResponse.GetSimpleValue('subitem1', FLogradouro);
{ ... }
GetSimpleValue
只能讀取 JSON 的頂級屬性作為響應。 它也非常低效,因為它在每次調用該方法時都會解析 JSON。
TRESTResponse
已經允許您通過其JSONValue
屬性訪問已解析的 JSON。 它允許您使用 JSON 路徑查詢整個結構中的值。 訪問JSONValue
屬性將僅解析響應一次,但請注意,如果響應為空或不是有效的 JSON,它可能會返回 nil。
另一點是您不必自己創建TRestResponse
。 它在LRequest.Execute
自動創建。 話雖如此,訪問返回的 JSON 中的值的代碼將是:
if not Assigned(LRequest.Response.JSONValue) then
raise Exception.Create('Invalid response.');
ShowMessage(LRequest.Response.JSONValue.GetValue<string>('Information.subitem1'));
您可以在 JSON 路徑中使用方括號作為數組訪問器來按索引訪問項目:
LRequest.Response.JSONValue.GetValue<string>('SomeStrings[0]');
你可以做:
RESTResponse1.JSONValue.GetValue<string>('Information.subitem1');
或者
var
LValue: string;
LJSONObject: TJSONObject;
begin
LJSONObject := RESTResponse1.JSONValue as TJSONObject;
LValue := LJSONObject.GetValue('subitem1').Value;
end;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.