Mapping of JSON-Name to Delphi-Name

Hi,

is it possible to map the json name to delphi name like this example

[httpPost] function webhook ([fromBody] [Name('message-id')] messageid:string):TStream

BREVO sends me a json with a field name
{"message-id" : "1234"}.
Of course message-id can not be used in delphi.

I suggest you use a DTO and then use JsonProperty attribute:

TWebhookPayload = class
private
  [JsonProperty('message-id')]
  FMessageId: string;
public
  property MessageId: string read FMessageId write FMessageId;
end;

...

[HttpPost] function webhook(Payload: TWebhookPayload): TStream;

Thank you! Yes, this was doing the trick, In the menatime I had other problems with the brevo webhook (the json structure changes depending of the event and I need Int64, a date is formated very special and so on ).
So I used now a TStream and the good old TJSONObject.ParseJSONValue(payload);

   V := TJSONObject.ParseJSONValue(S);
   if v <>nil then
   begin
      V.TryGetValue<string>('event', event);
      V.TryGetValue<string>('email', email);
      V.TryGetValue<integer>('id', id);
      V.TryGetValue<integer>('ts', ts);
      V.TryGetValue<string>('message-id', messageid);
      V.TryGetValue<string>('subject', subject);
      V.TryGetValue<string>('reason', reason);
  end;

It's not "nice" but it works

Thank you for the hint!!!

You can simply declare the parameter as TJSONObject. XData will do the rest for you:

[HttpPost] function webhook(Payload: TJSONObject): TStream;

This shortway is very interesting. Thank you..

function TWebHookService.WebHook(payload: TJsonObject): TJsonObject;
Var
  event:string;
  email:string;
  id:integer;
  ts:integer;
  messageid:string;
  subject:String;
  reason:string;
begin
  payload.TryGetValue<string>('event', event);
  payload.TryGetValue<string>('email', email);
  payload.TryGetValue<integer>('id', id);
  payload.TryGetValue<integer>('ts', ts);
  payload.TryGetValue<string>('message-id', messageid);
  payload.TryGetValue<string>('subject', subject);
  payload.TryGetValue<string>('reason', reason);
  TWebHook_DBCtrl.SaveWebHook(event, email, id, date, ts, messageid, subject, reason);

  Result := TJsonObject
    .Create
    .AddPair('event', event)
    .AddPair('status', 'ok');

end;
1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.