使用 jsonobject.count 和对时出错



我想通过以下示例处理 json 字符串:

{"colors":[{"name":"red","hex":"#f00"},{"name":"blue","hex":"#xxx"}]}

我尝试了不同的变体,并收到以下错误:

Tjsonobject 不包含名为"Count"的成员...
Tjsonobject 不包含名为"Pairs"的成员...
未声明的标识符 JsonString...

我穿上使用DBXJson
Delphi 10.2.3,vcl应用程序

代码为:

var
o: TJSONObject;
a: TJSONArray;
book: TJSONObject;
idx: integer;
idy: integer;
begin
o := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(Memo1.Lines.Text),0) as TJSONObject;
try
a := TJSONArray(o.Get('colors').JsonValue);
for idx := 0 to pred(a.size) do begin
book := TJSONObject(a.Get(idx));
for idy := 0 to pred(book.Count) do begin
ShowMessage( book.Pairs[idy].JsonString.ToString + ':' + book.Pairs[idy].JsonValue.ToString );
end;
end;
finally
o.Free;
end;
end;

JSON中的新功能,用于学习,但我无法弄清楚

您的问题和评论是矛盾的。您的问题说您正在使用 Delphi 10.2.3,但您的评论说您正在使用 XE5。

在 Delphi 10.2.3 中,使用System.JSON单位。在 XE5 中,使用Data.DBXJson单元。

如果您阅读 XE5 版本的文档TJSONObject,它没有CountPairs属性,因此您在内部循环中看到错误。您应该改用TJSONObject.Size属性和TJSONObject.Get()方法,就像您的外部循环已经在使用一样,例如:

var
o: TJSONObject;
a: TJSONArray;
book: TJSONObject;
p: TJSONPair;
idx: integer;
idy: integer;
begin
o := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(Memo1.Lines.Text),0) as TJSONObject;
try
a := o.Get('colors').JsonValue as TJSONArray;
for idx := 0 to pred(a.Size) do
begin
book := a.Get(idx).JsonValue as TJSONObject;
for idy := 0 to pred(book.Size) do
begin
p := book.Get(idy);
ShowMessage(p.JsonString.ToString + ':' + p.JsonValue.ToString);
end;
end;
finally
o.Free;
end;
end;

或者,XE5 和 10.2.3 中的TJSONArrayTJSONObject都有Enumerator支持,因此您可以改用for..in循环,例如:

var
o: TJSONObject;
a: TJSONArray;
book: TJSONObject;
v: TJSONValue;
p: TJSONPair;
begin
o := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(Memo1.Lines.Text),0) as TJSONObject;
try
a := o.Get('colors').JsonValue as TJSONArray;
for v in a do
begin
book := v as TJSONObject;
for p in book do
begin
ShowMessage(p.JsonString.ToString + ':' + p.JsonValue.ToString);
end;
end;
finally
o.Free;
end;
end;

如果你正在学习如何在delphi中使用json,我建议你不要使用system.json,太复杂而且非常慢。 看看 TalJsonDocument 在 https://github.com/Zeus64/alcinoe

MyJsonDoc.loadFromJson('{"colors":[{"name":"red","hex":"#f00"},{"name":"blue","hex":"#xxx"}]}');
for i := 0 to MyJsonDoc.childnodes['colors'].ChildNodes.count - 1 do begin
writeln(MyJsonDoc.childnodes['colors'].childnodes[i].childnodes['name'].text);
writeln(MyJsonDoc.childnodes['colors'].childnodes[i].childnodes['hex'].text);
end;

最新更新