我使用的是 Delphi XE8。
我只是在看REST.Json ObjectToJsonString()
和JsonToObject()
来电。
主要尝试做这样的事情:
How to convert an object to JSON and back with a single line of code
我注意到,只有当变量以 F
开头时,我才能使变量起作用。特点。我找不到任何关于此的文档。这是预期的行为吗?我应该用 F
命名类中的所有变量吗?在开始时?如果是,有人可以解释为什么吗?
我创建了一个类TTestJSON
并定义了两个成员变量并将它们设置为“WORKS”和“FAILS”。
然后我从该对象创建了一个 JSON 字符串值:
{
"varThatWorksBeacuseItStartsWithF":"WORKS",
"sVarThatFailsBecauseItStartsWithS":"FAILS"
}
从 JSON 字符串返回到对象时,只有 fVarThatWorksBeacuseItStartsWithF
变量正在正确重置。在下面的代码中,test := TJson.JsonToObject<TTestJSON>(JsonStr);
使用上面的 JSON,请注意 sVarThatFailsBecauseItStartsWithS
是 ""
而不是"FAILS"
.
procedure TForm3.btn1Click(Sender: TObject);
var
test : TTestJSON;
JsonStr : String;
begin
m1.Clear;
test := TTestJSON.Create;
try
test.fVarThatWorksBeacuseItStartsWithF := 'WORKS';
test.sVarThatFailsBecauseItStartsWithS := 'FAILS';
JsonStr := TJson.ObjectToJsonString( test );
finally
test.Free;
end;
m1.Lines.Add( '** JSONStr Value START **' + #13#10 + JsonStr + '** JSONStr Value END **' + #13#10 );
test := TJson.JsonToObject<TTestJSON>(JsonStr);
try
m1.Lines.Add('** Obj loaded from JSON String Start **' + #13#10 + TJson.ObjectToJsonString( test ) + #13#10 + '** Obj loaded from JSON String End **');
finally
test.Free;
end;
end;
从结果来看,以f
开头的var有f
从 JSON 字符串中删除,以及以 s
开头的字符串仍然有它在那里。我本以为第二个结果会是这样的:
{
"varThatWorksBeacuseItStartsWithF":"WORKS",
"sVarThatFailsBecauseItStartsWithS":"FAILS"
}
这里是要重现的完整代码 - 在 vcl 表单上只有一个按钮和一个备忘录 - 还使用 REST.Json:
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, rest.Json;
type
TTestJSON = class
fVarThatWorksBeacuseItStartsWithF : String;
sVarThatFailsBecauseItStartsWithS : String;
end;
TForm3 = class(TForm)
btn1: TButton;
m1: TMemo;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
{$R *.dfm}
procedure TForm3.btn1Click(Sender: TObject);
var
test : TTestJSON;
JsonStr : String;
begin
m1.Clear;
test := TTestJSON.Create;
try
test.fVarThatWorksBeacuseItStartsWithF := 'WORKS';
test.sVarThatFailsBecauseItStartsWithS := 'FAILS';
JsonStr := TJson.ObjectToJsonString( test );
finally
test.Free;
end;
m1.Lines.Add( '** JSONStr Value START **' + #13#10 + JsonStr + '** JSONStr Value END **' + #13#10 );
test := TJson.JsonToObject<TTestJSON>(JsonStr);
try
m1.Lines.Add('** Obj loaded from JSON String Start **' + #13#10 + TJson.ObjectToJsonString( test ) + #13#10 + '** Obj loaded from JSON String End **');
finally
test.Free;
end;
end;
end.
最佳答案
该库序列化字段。由于常见的做法是在字段前添加字母 F,因此设计者希望从 JSON 中使用的名称中删除该字母。因此,他们决定将默认行为设为去掉名称以 F 开头的字段中的第一个字母。坦率地说,这对我来说似乎很奇怪。
可以使用属性自定义此行为。例如:
[JSONMarshalled(False)]
FFoo: Integer;
[JSONMarshalled(True)]
[JSONName('Blah')]
Bar: Integer;
据我所知,这些都没有正确记录。
关于json - Delphi Rest.JSON JsonToObject 仅适用于 f 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31778518/