我想決議 JSON 并提取所有 ID 值并分配,在組合框中顯示它們。我正在使用 ULKJson 庫和 Delphi 7。這是我的 JSON
{
"ID": null,
"ResCode": 100,
"ResMessage": "??? ???? ????? ?? ?????? ???? ????? ???",
"ResPos": null,
"ResData": {
"data": [
{
"data": {
"id": "2994LUZUWL",
"type": "SHEBAD_ID"
},
"sendDate": "2021-11-02T20:00:16.827"
},
{
"data": {
"id": "2992CQVAE1",
"type": "SHEBAD_ID"
},
"sendDate": "2021-11-02T18:43:12.857"
},
{
"data": {
"id": "Z2005KUU6ZB",
"type": "SHEBAD_ID"
},
"sendDate": "2021-11-02T18:51:36.107"
},
{
"data": {
"id": "Z29914MM2WL",
"type": "SHEBAD_ID"
},
"sendDate": "2021-11-02T19:21:08.607"
}
],
"message": "",
"succeeded": true
}
}
如何訪問此 JSON 中的 ID 值?
uj5u.com熱心網友回復:
Delphi 6 用戶在這里,但同樣的事情真的..
您需要安裝 uLKJson,我假設您已經安裝了。
您需要將每個元素決議為 uLKJSON 型別之一:
jsBase, jsNumber, jsString, jsBoolean, jsNull, jsList, jsObject
你有
{ <<< root = object
"ResData": { <<< ResData = object
"data": [ <<< data = list
{ <<< element[0] = object
"data": { <<< data = object
"id": "2994LUZUWL", <<< id = string. This is what you want.
...
在 jq 中,這將是選擇字串:".ResData.data[].data.id"。
決議資料的程式可能如下所示:
program testparse;
{$APPTYPE CONSOLE}
uses
SysUtils, // for writing on console
ulkjson; // to parse JSON
var
vJsonObj: TlkJsonObject;
jo : TlkJSONstreamed;
listofelements: TlkJSONlist;
i : integer;
// {
// "data": {
// "id": "2994LUZUWL",
// "type": "SHEBAD_ID"
// },
// "sendDate": "2021-11-02T20:00:16.827"
// },
// function for simplicity
//
function get_key( j : TlkJSONobject) : string;
begin
try
result := j.Field['data'].Field['id'].Value;
except
result := 'N/A'; // if the id key is not there..
end;
end;
begin
jo := TlkJSONstreamed.Create;
try
vJsonObj := jo.LoadFromFile('jsontext.txt') as TlkJsonObject;
listofelements := vJsonObj.Field['ResData'].Field['data'] as TlkJSONlist;
for i := 0 to listofelements.Count-1 do
begin
writeln('Key no ' inttostr(i) '='
get_key(listofelements.Child[i] as TlkJSONobject)
);
end;
finally
jo.free;
end;
end.
結果:
Key no 0=2994LUZUWL
Key no 1=2992CQVAE1
Key no 2=Z2005KUU6ZB
Key no 3=Z29914MM2WL
替代庫
或者,可以使用最初來自 Lazarus 的JSONTools 。我已經修改并上傳了 Delphi 6/7 的版本。
使用本機:
writeln('-- doing it with JSONTools');
N := TJsonNode.Create;
n.LoadFromFile('jsontext.txt'); // will automatically do a parse
n:= n.Find('/ResData/data'); // get the array
for i := 0 to n.Count-1 do
begin
writeln(
'Key no ' inttostr(i) '='
n.Child(i).Find('data/id').AsString);
end;
n.Free;
添加到組合框
因為問題是如何添加到組合框:這很簡單。首先清除組合框,然后為每個專案做一個“additem”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/509904.html
標籤:json德尔福德尔福7
