delphi 如何用TJSONIterator填充TListView.下一步?

jm81lzqq  于 2023-01-02  发布在  其他
关注(0)|答案(1)|浏览(152)

我有一个TListView的应用程序,我想使用TJSONIterator.Next()从JSON填充Items中的数据。我使用的代码显示了我想要的结果,除了第一个。
我怎样才能正确地解析这些JSON对象,我做错了什么?

数据:Data.json

{
  "event":"subscribe-status",
  "status":"ok",
  "success":[
    {
      "symbol":"EUR/USD",
      "exchange":"PHYSICAL CURRENCY",
      "mic_code":"PHYSICAL CURRENCY",
      "country":"",
      "type":"Physical Currency"
    },
    {
      "symbol":"USD/JPY",
      "exchange":"PHYSICAL CURRENCY",
      "mic_code":"PHYSICAL CURRENCY",
      "country":"",
      "type":"Physical Currency"
    },
    {
      "symbol":"BTC/USD",
      "exchange":"Coinbase Pro",
      "mic_code":"Coinbase Pro",
      "country":"",
      "type":"Digital Currency"
    },
    {
      "symbol":"ETH/BTC",
      "exchange":"Huobi",
      "mic_code":"Huobi",
      "country":"",
      "type":"Digital Currency"
    }
  ],
  "fails":null
}

代码应用程序:

LStringReader := TStreamReader.Create('../../Data.json', TEncoding.UTF8, True);
LJsonTextReader := TJsonTextReader.Create(LStringReader);
LIterator := TJSONIterator.Create(LJsonTextReader);
NObjJSON := LIterator.AsInteger;
    
ListView1.Items.Clear;
ListView1.BeginUpdate;
try
  while True do
  begin
    while LIterator.Next do
    begin
      if LIterator.&Type in [TJsonToken.StartObject, TJsonToken.StartArray] then
      begin
        LIterator.Recurse;
        LIterator.Next;
        oItem := ListView1.Items.Add;
        for NObjJSON := 0 to ListView1.ItemCount -1 do
        begin
          oItem.Text := 'Object #' + NObjJSON.ToString + ' ' + LIterator.AsValue.ToString;
          oItem.Detail := 'Key:' +LIterator.Key;
        end
      end;
    end;
    if LIterator.InRecurse then
      LIterator.Return
    else
      Break;
  end;
finally
  ListView1.EndUpdate;
  LIterator.Free;
  LJsonTextReader.Free;
  lStringReader.Free;
  Memo1.Lines.Text := NObjJSON.ToString;
end;
mec1mxoz

mec1mxoz1#

在循环的开头添加recurse / next,为输入array做准备:

while LIterator.Next do
begin
  if LIterator.&Type = TJsonToken.StartArray then
  begin
    LIterator.Recurse;
    LIterator.Next;
  end;

您可以在文档中查看此示例:https://docwiki.embarcadero.com/CodeExamples/Sydney/en/RTL.JSONIterator
下面的代码更容易阅读:

procedure TFormX.LoadJSON;
const
  cValue = 'symbol';
var
  LValue: TJSONValue;
  LArray: TJSONArray;
  i: integer;
  oItem: TListViewItem;
begin
  LValue := TJSONObject.ParseJSONValue('{json}');

  LArray := LValue.FindValue('success') as TJSONArray;

  if Assigned(LArray) then
  begin
    for i := 0 to LArray.Count - 1 do
    begin
      oItem := ListView1.Items.Add;

      oItem.Text := 'Object #' + i.ToString + ' ' + LArray.Items[i].GetValue<string>(cValue);
      oItem.Detail := 'Key:' + cValue;
    end;
  end;
end;

相关问题