Home > front end >  Delphi Alexandria - Backward slash in JSON response
Delphi Alexandria - Backward slash in JSON response

Time:07-08

In JSON response, backward slashes are included in string if we have forward slash character.

I am using the below code to get the API response.

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;

In API Response, backward slashes are included in string if I had forward slash in it. For Example,

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

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

This is happening only in Alexandria version of Delphi whereas it was working fine in Delphi Berlin.

All I want to remove the backward slash in string. Please help me

CodePudding user response:

You don't have to remove anything. Just parse valid json response and you will obtain the correct field value without escaped json string, just like @Dave Nottage and @Adriaan mentioned in comments.

See below two alternatives to parse with System.json and mORMot. It was tested with Delphi 10.x and Delphi 11 versions.

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.
  • Related