从JSON数组中提取特定值

时间:2017-07-15 17:32:34

标签: json delphi

我有一个以这种方式格式化的JSON响应:

- Client 1
  - Date: 15.07.2017
  - Name: John
  - URL: www.google.com
- Client 2
  - Date: 15.07.2017
  - Name: Jane
  - URL: www.google.com
- Client N...

我怎么才能只提取姓名&来自每个客户端的URL值,以便我可以将它们添加到列表框中,例如?另请注意"客户1"可以用其他方式命名,例如"用户1和#34;或者只是" 1",这并不重要,但代码应该提取值而不管父对象名称。

PS:对于误导,上面的JSON格式是来自内存的伪代码,实际格式为:

[
  {
    "date":"xxx", 
    "name":"xxx", 
    "url":"xxx"
  }, 
  {
    "date":"xxx", 
    "name":"xxx", 
    "url":"xxx"
  }, 
  {
    "date":"xxx", 
    "name":"xxx", 
    "url":"xxx"
  }
]

1 个答案:

答案 0 :(得分:3)

如果有人在看,请回答。

procedure Answer;
var
  JSON: string;
  ClientItem: TJSONValue;
  ClientList: TJSONArray;
  ListBoxItem: TListBoxItem;
begin
  JSON := TFile.ReadAllText('.\your-file.json');
  ClientList := TJSONObject.ParseJSONValue(JSON) as TJSONArray;
  if Assigned(ClientList) then
  try
    ListBox.Items.BeginUpdate;
    try
      for ClientItem in ClientList do
      begin
        ListBoxItem := TListBoxItem.Create(ListBox);
        ListBoxItem.StyleLookup := 'CustomListbox';
        ListBoxItem.StylesData['URL'] := ClientItem.GetValue<string>('url');
        ListBoxItem.StylesData['Name'] := ClientItem.GetValue<string>('name');
        Listbox.AddObject(ListBoxItem);
      end;
    finally
      Listbox.Items.EndUpdate;
    end;
  finally
    ClientList.Free;
  end;
end;