Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi object to json string how to ignore empty and null fields

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.

like image 775
pikk Avatar asked Aug 31 '25 20:08

pikk


1 Answers

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;
like image 102
Cleidson Barbosa Avatar answered Sep 04 '25 02:09

Cleidson Barbosa