获取JSON数组并将项目添加到Delphi中的Combobox

时间:2016-10-03 06:27:28

标签: json delphi combobox

我有这个JSON数据:

[
  {
    "Name":"val1",
    "Age":"25"
  },
  {
    "Name":"Vtya",
    "Age":"24"
  },
  {
    "Name":"fgani",
    "Age":"21"
  },
  {
    "Name":"Shami",
    "Age":"21"
  },
  {
    "Name":"Slakf",
    "Age":"22"
  }
]

我编写了这段代码来解析数据并将Name值添加到Combobox:

procedure TJSON_Sample.FormCreate(Sender: TObject);
var
  LJsonArray: TJSONArray;
  LJsonValue, LITEM: TJSONValue;
  lJsonData: string;
  ljsPair: TJsonPair;
begin
  LJsonArray := TJSONObject.ParseJSONValue(TEncoding.
    Default.GetBytes(lJsonData), 0) as TJSONArray;//lJsonData contains the above mentioned JSON data
  try
    for LJsonValue in LJsonArray do
    begin
      for LITEM in TJSONArray(LJsonValue) do
      begin
        cmbBox_Name.Items.Add(TJsonPair(LITEM).JsonValue.Value);
      end;
    end;
  finally
    LJsonArray.Free;
  end;
end;

当我运行它时,它会将所有名称和年龄添加到组合框中。有人可以帮我添加名字吗?

4 个答案:

答案 0 :(得分:2)

您的代码通过JSON循环正常。您的问题是在将项目添加到组合框时只获取“名称”值。

尝试GetValue('Name')而不是整个JSONValue.Value。

procedure TJSON_Sample.FormCreate(Sender: TObject);
var
  LJsonArray: TJSONArray;
  LJsonValue, LITEM: TJSONValue;
  lJsonData: string;
  ljsPair: TJsonPair;
begin
  LJsonArray := TJSONObject.ParseJSONValue(TEncoding.
    Default.GetBytes(lJsonData), 0) as TJSONArray;//lJsonData contains the above mentioned JSON data
  try
    for LJsonValue in LJsonArray do
    begin
      for LITEM in TJSONArray(LJsonValue) do
      begin
        cmbBox_Name.Items.Add(TJsonObject(LITEM).GetValue('Name').Tostring);
      end;
    end;
  finally
    LJsonArray.Free;
  end;
end;

答案 1 :(得分:1)

这解决了我的要求

/^(?:(?:(?:0[13578]|1[02])(\/)31)\1|(?:(?:0[1,3-9]|1[0-2])(\/)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:02(\/)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\/)(?:0[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/

答案 2 :(得分:0)

我会考虑使用Items.AddObject方法,并在组合框的OnChange事件上使用Items.Object[ComboBox1.ItemIndex]

答案 3 :(得分:0)

这里几乎是相同的代码,但我为组合框项添加BeginUpdate/EndUpdate并使用泛型方法来避免类型转换。

procedure TJSON_Sample.FormCreate(Sender: TObject);
var
  LJson, LItem: TJSONValue;
  lJsonData: string;
begin
  cmbBox_Name.Items.BeginUpdate;
  try
    cmbBox_Name.Items.Clear;

    LJson := TJSONObject.ParseJSONValue(TEncoding.
      Default.GetBytes(lJsonData), 0);//lJsonData contains the above mentioned JSON data

    if Assigned(LJson) then
    begin
      for LItem in LJson as TJSONArray do
        cmbBox_Name.Items.Add(LItem.GetValue<string>('Name'));
    end;
  finally
    cmbBox_Name.Items.EndUpdate;
  end;
end;