4

I have a class for rest request as follows

TRedeemItemsClass = class
private
  [JSONName('RedeemCode')]
  FRedeemCode: String;
  [JSONName('AssetKey')]
  FAssetKey:String;
public
  property RedeemCode: String read FRedeemCode write FRedeemCode;
  property AssetKey:String read FAssetKey write FAssetKey;
  function ToJsonString: string;
  class function FromJsonString(AJsonString: string): TRedeemItemsClass;
end;

implementation

function TRedeemItemsClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self);
end;

class function TRedeemItemsClass.FromJsonString(AJsonString: string): TRedeemItemsClass;
begin
  result := TJson.JsonToObject<TRedeemItemsClass>(AJsonString)
end;

jObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(reqRedeem.ToJsonString), 0) as TJSONObject;

Using this line of code I get my json request string like

{"RedeemCode":"","AssetKey":"xxxxx"}

as expected.

Redeem request body json string should either one of these ( according to information received from the customer assetkey or redeemcode)

{"RedeemItems":[{"AssetKey":"xxxxx"}]}

or

{"RedeemItems":[{"RedeemCode":"xxxxx"}]}

So in the short term, I want to ignore all fields (including arrays) that is empty or nil.

I'm using Delphi 10 Seattle.

2

2 Answers 2

2

You can use the below method:

function TRedeemItemsClass.ToJsonString: string;
begin
  result := TJson.ObjectToJsonString(self, [TJsonOption.joIgnoreEmptyStrings]);
end;

or

function TRedeemItemsClass.ToJsonObject: TJSONObject;
begin
  result := TJson.ObjectToJsonObject(self, [TJsonOption.joIgnoreEmptyStrings]);
end;
Sign up to request clarification or add additional context in comments.

Comments

0

You can simply check it's nil condition:

if Assigned(field) then
begin
  // do something
end;

or

if field <> nil then
begin
  // do something
end;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.