情况如下:
uses
System.JSON;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
dd:Double;
aJsonObj:TJSONObject;
begin
dd := 100.0;
aJsonObj := TJSONObject.Create(TJSONPair.Create('DecimalValue',TJSONNumber.Create(dd)));
ShowMessage(aJsonObj.ToString);
end;
显示
{"DecimalValue":100}
我需要的是
{"DecimalValue":100.0}
我尝试更改 JsonFormatSettings
但找不到添加小数部分的方法。
最佳答案
TJSONNumber
constructors 之一接受将在生成的 JSON 字符串中使用的原始字符串值,无需进一步处理。它允许您自己预先格式化该值:
procedure TForm1.Button1Click(Sender: TObject);
var
dd: Double;
aJsonObj: TJSONObject;
begin
dd := 100.0;
aJsonObj := TJSONObject.Create(
TJSONPair.Create('DecimalValue', TJSONNumber.Create(FormatFloat('0.0###', dd, GetJSONFormat))));
try
ShowMessage(aJsonObj.ToString);
finally
aJsonObj.Free;
end;
end;
使用上面的代码片段,值显示为:
{"DecimalValue":100.0}
您甚至可以创建'whatever'
作为数字:
aJsonObj := TJSONObject.Create(TJSONPair.Create('DecimalValue', TJSONNumber.Create('whatever')));
获取此(无效)JSON:
{"DecimalValue":whatever}
旁注:您有责任释放您创建的根 JSON 对象,因为它们没有父对象来管理其生命周期。完成后,使用 try..finally
来释放
根对象,如第一个代码片段中所示。太糟糕了the documentation它本身就会诱惑你不去清理。
关于json - 当值为整数时,无法将小数部分显示为 .0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64139798/