Parse JSON with Web Core TMS

112 Views Asked by At

I have a simple API call. When I do the call I know it's sending the correct data, because I get the correct response:

{
    "success": true,
    "data": {
        "accessToken": "eyJ0eXAiOiJKV1QiL....",
        "token_type": "bearer"
    },
    "message": "Login Successful"
}

But I cannot figure out how to save the accessToken value or the token_type value or even the success and message values. This is my current code:

procedure TForm1.WebButton1Click(Sender: TObject);
var
  AccessToken, TokenType: String;
begin
  AccessToken := '';
  TokenType := '';

  APIConnection.URL := 'https://aaa/api/login';
  APIConnection.Command := httpPOST;
  APIConnection.Headers.Clear;
  APIConnection.Headers.AddPair('Content-Type','application/json');
  APIConnection.Headers.AddPair('Accept','application/json, text/plain, */*');
  APIConnection.PostData := '{"email":"[email protected]","password":"123456789"}';
  APIConnection.Execute(
    procedure(AResponse: String; AReq: TJSXMLHttpRequest)
    var
      js: TJSON;
      ja: TJSONArray;
      jo: TJSONObject;
      i: Integer;
    begin
      js := TJSON.Create;

      try
        ja := TJSONArray(js.Parse(AResponse));

        ShowMessage('Retrieved items:' + IntToStr(ja.Count));

        for i := 0 to ja.Count - 1 do
        begin
          jo := TJSONObject(ja.Items[i]);
          WebListBox1.Items.Add(jo.GetJSONValue('data'));
        end;
      finally
        js.Free;
      end;
    end
  );
end;

I did a test to see what the Response was reading, and maybe this is the issue? But the response value is blank, but the Response value in debugger is correct.

procedure TForm1.APIConnectionRequestResponse(Sender: TObject;
  ARequest: TJSXMLHttpRequestRecord; AResponse: string);
var
JS : TJSON;
begin
   JS := TJson.Create;
   showmessage('Response: '+AResponse+'  :END');

end;

enter image description here

1

There are 1 best solutions below

4
Matthias B On

Your example JSON does not contain any array. Instead, your JSON contans an object, with key-value pairs. You can get the values like this:

uses
  System.JSON;

procedure(const AResponse: string; AReq: TJSXMLHttpRequest);
var
  jv: TJSONValue;
  AccessToken, TokenType: string;
begin
  jv := TJSONObject.ParseJSONValue(AResponse);

  AccessToken := jv.FindValue('data').FindValue('accessToken').AsType<string>;
  TokenType := jv.FindValue('data').FindValue('token_type').AsType<string>;

  WebListBox1.Items.Add(AccessToken);
  WebListBox1.Items.Add(TokenType);
end;

I don't know how to handle Boolean (except simplistically handling it as a string). Maybe some else can extend this answer.