Delphi Alexandria - JSON 响应中的反斜杠

问题描述 投票:0回答:2

在 JSON 响应中,如果我们有正斜杠字符,则反斜杠包含在字符串中。

我正在使用下面的代码来获取 API 响应。

procedure GetJSONInformation;
var
  objResponse : TRESTResponse;
  objClient : TRESTClient;
  objRequest : TRESTRequest;
  sJSONResponse : string;
begin
  objResponse  := TRESTResponse.Create(nil);
  objClient := TRESTClient.Create(nil);
  objClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
  objClient.AcceptCharset := 'UTF-8, *;q=0.8';
  objRequest := TRESTRequest.Create(nil);
  objRequest.Method := rmGET;
  objRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
  objRequest.AcceptCharset := 'UTF-8, *;q=0.8';
  objRequest.Client := objClient;
  objRequest.Response:= objResponse;
  try
    objClient.BaseURL := 'https://sample.net';
    ObjRequest.Resource := 'api/GetInformation/{Param1}/{Param2}';
    ObjRequest.AddParameter('Param1', 'Parameter1', TRESTRequestParameterKind.pkURLSEGMENT);
    ObjRequest.AddParameter('Param2', 'Parameter2', TRESTRequestParameterKind.pkURLSEGMENT);
    ObjRequest.Execute;
    if ObjResponse.StatusCode = 200 then
      sJSONResponse:= ObjResponse.JsonText;  //Here i got the JSON response
  finally
    FreeAndNil(objRequest);
    FreeAndNil(objClient);
    FreeAndNil(objResponse);
  end;
end;

在 API 响应中,如果我在字符串中有正斜杠,则反斜杠包含在字符串中。例如,

JSON Response:  "Date": "04\/13\/2022",
                "stringdata": "DEC\/ACB test",

Expected Response:  "Date": "04/13/2022",
                    "stringdata": "DEC/ACB test",

这仅在 Delphi 的 Alexandria 版本中发生,而在 Delphi Berlin 中运行良好。

All 我想删除字符串中的反斜杠。请帮助我

json delphi delphi-10.1-berlin delphi-11-alexandria
2个回答
0
投票

您不必移除任何东西。 只需解析有效的 json 响应,您将获得没有转义 json 字符串的正确字段值,就像评论中提到的 @Dave Nottage 和 @Adriaan 一样。

请参阅以下两种使用 System.json 和 mORMot 进行解析的替代方法。它已使用 Delphi 10.x 和 Delphi 11 版本进行测试。

program Test_SystemJson_and_mORMot;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.JSON,
  Syncommons;

const
  ValidJSON='{"Date": "04\/13\/2022","stringdata": "DEC\/ACB test"}';
var
  // with System.JSON
  JsonValue : TJSonValue;
  // with mORMot
  Json : variant;
begin
  // with System.JSON
  JsonValue := TJSonObject.ParseJSONValue(ValidJSON);
  writeln(JsonValue.GetValue<string>('Date')); // Result 04/13/2022
  writeln(JsonValue.GetValue<string>('stringdata')); // Result DEC/ACB test

  // with mORMot
  Json := _Json(ValidJSON);
  writeln(Json.Date); // Result 04/13/2022
  writeln(Json.stringdata); // Result DEC/ACB test
  readln;
end.

0
投票

从 Embarcadero Quality 门户网站找到了 Marco Cantù 关于此行为的回复,他提到可以使用

TJSONPair.JsonValue.Value
获取 JSON 原始值。尝试过并且似乎按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.