简体   繁体   English

Delphi对象转json字符串如何忽略空字段和空字段

[英]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使用这行代码,我得到了我的 json 请求字符串,例如

{"RedeemCode":"","AssetKey":"xxxxx"} {"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 )兑换请求正文 json 字符串应该是其中之一(根据从客户资产密钥兑换码收到的信息)

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

or或者

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

So in the short term, I want to ignore all fields (including arrays) that is empty or nil.所以在短期内,我想忽略所有为空或 nil 的字段(包括数组)。

I'm using Delphi 10 Seattle.我正在使用 Delphi 10 Seattle。

You can simply check it's nil condition:您可以简单地检查它的nil条件:

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

or或者

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

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM