我正在将一些项目从 Delphi 10.4 迁移到 Delphi 11.3。 我在使用 JSON 库时遇到一些问题:
请参阅以下代码:
第一种情况:
function TestCreate;
var
LValue: Variant;
LJSON: TJSONNumber;
begin
LValue := 100;
LJSON := TJSONNumber.Create(LValue);
end;
编译它,结果是:
[dcc64 Error] _Unit.pas(74): E2251 Ambiguous overloaded call to 'Create'
System.JSON.pas(435): Related method: constructor TJSONNumber.Create(const string);
System.JSON.pas(439): Related method: constructor TJSONNumber.Create(const Double);
第二种情况:
function TestAddPair;
var
LValue: Variant;
LJSON: TJSONObject;
begin
LValue := 100;
LJSON := TJSONObject.Create();
LJSON.AddPair('Test', LValue);
end;
编译它,结果是:
[dcc64 Error] _Unit.pas(77): E2251 Ambiguous overloaded call to 'AddPair'
System.JSON.pas(661): Related method: function TJSONObject.AddPair(const string; const Boolean): TJSONObject;
System.JSON.pas(651): Related method: function TJSONObject.AddPair(const string; const Double): TJSONObject;
System.JSON.pas(636): Related method: function TJSONObject.AddPair(const string; const string): TJSONObject;
两者都曾经在 Delphi 10.4 上正常工作,但在 Delphi 11.3 上它们无法编译。 有没有办法让他们编译?我不想修改每个使用 Variant 创建/添加 JSON 的命令。
最佳答案
Variant 可以隐式转换为字符串或 Double 类型,而无需选择其中之一。
在 R104 中,采用字符串参数的构造函数受到保护,而在 11.3 中它是公共(public)的。
正如 Toon 提到的,您可能无法避免更改所有调用。
更新:或者,您可以为 TJSONNumber
和 TJSONObject
创建类帮助器,并覆盖 Variant。 F.i.像这样:
type
TJSONNumberHelper = class helper for TJSONNumber
public
constructor Create(const AValue: Variant); overload;
end;
constructor TJsonNumberHelper.Create(const AValue: Variant);
begin
inherited Create(Double(AValue));
end;
关于json - Delphi 11.3 - 无法从变体创建/添加 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76463926/