gpt4 book ai didi

json - 为什么 TJson.ObjectToJsonObject/ObjectToJsonString 将记录字段表示为 JSON 数组?

转载 作者:行者123 更新时间:2023-12-03 15:58:08 34 4
gpt4 key购买 nike

SuperObject 和 TJson.ObjectToJsonObject 表示类的某些部分(即记录字段)的方式不一致。让我们看一下以下代码片段:

Uses rest.json, superobject;

type

TSimplePersonRec = record
FirstName: string;
LastName: string;
Age: byte;
end;

TSimplePerson = class
protected
FPersonRec: TSimplePersonRec;
public
property personRecord: TSimplePersonRec read FPersonRec write FPersonRec;
end;

// ...

{ Public declarations }
function toJson_SO(simplePerson: TSimplePerson): string;
function toJson_Delphi(simplePerson: TSimplePerson): string;

// ...

function TForm1.toJson_Delphi(simplePerson: TSimplePerson): string;
begin
result := tjson.Format(TJson.ObjectToJsonObject(simplePerson));
end;

function TForm1.toJson_SO(simplePerson: TSimplePerson): string;
var
so: ISuperObject;
ctx: TSuperRttiContext;
begin
ctx := TSuperRttiContext.Create;
try
so := ctx.AsJson<TSimplePerson>( simplePerson );
finally
ctx.Free;
end;
result := so.AsJSon(true, true);
end;

// ...

procedure TForm1.Button3Click(Sender: TObject);
var
spr: TSimplePersonRec;
sp: TSimplePerson;
begin

spr.FirstName := 'John';
spr.LastName := 'Doe';
spr.Age := 39;

sp := TSimplePerson.Create;
sp.personRecord := spr;

memo1.Lines.Add(#13'--- SuperObject ---'#13);
memo1.Lines.Add(toJson_SO(sp));
memo1.Lines.Add(#13'--- Delphi ---'#13);
memo1.Lines.Add(toJson_Delphi(sp));
end;

输出是:

--- SuperObject ---
{
"FPersonRec": {
"LastName": "Doe",
"Age": 39,
"FirstName": "John"
}
}
--- Delphi ---
{
"personRec":
[
"John",
"Doe",
39
]
}

Delphi 将记录表示为 JSON 数组的原因是什么?是否有公共(public)标准或建议导致这一点?

注意:对我来说,用 {key: value} 表示法而不是数组来表示记录更自然。不知道该值所属的键名称可能会在反序列化期间产生奇怪的结果。例如,在反序列化期间,我可以传递一个具有相同布局的新类,其中包含具有不同内存布局的记录。在这种情况下,这些值将被随机分配,或者可能会发生 AV?

更新:我用的是德尔福XE7。我还发现了 json.org:

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

所以问题可能更多是关于这是 TJson 单元中的错误吗?

最佳答案

Delphi 输出是合法的 JSON。在内部,REST.TJson 被硬编码以将记录编码为 JSON 数组。这就是它的实现方式,它是设计使然,而不是错误。它只是表示数据的另一种方式。 SuperObject 选择更加明确。那也可以。两种不同的实现,两种不同的表示。 JSON 规范允许两者兼而有之。

关于json - 为什么 TJson.ObjectToJsonObject/ObjectToJsonString 将记录字段表示为 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25834948/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com