如何从 Delphi 中的 TRESTReponse 获取子项值?

How to get the subitem value from a TRESTReponse in Delphi?

我需要获取包含以下 JSON 的 LResponsesubitem1 值:

"Information": {
    "subitem1": "2011",
    "subitem2": "Test"
}

我正在使用此代码获取其他值,它运行良好,但是当我尝试获取 Informationsubitem1subitem2 时,它返回一个空值.

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 属性 只会解析一次响应,但要注意它可能 return nil,如果响应为空或不是有效的 JSON.

另一点是您不必自己创建 TRestResponse。它是在 LRequest.Execute 中自动创建的。话虽如此,访问 returned 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;