我需要決議來自 Firebase 資料庫的以下 JSON 回應。在這個 JSON 示例中,有 2 個檔案qouap9和15p3vl. 兩個檔案都有多個欄位。我想將每個檔案中的所有欄位字串合并為一行。
{
"documents": [
{
"name": "projects/..",
"fields": {
"qouap9": {
"stringValue": "A1:Hello;"
},
"5": {
"stringValue": "A9:..."
},
"6": {
"stringValue": "A10:..."
}
},
"createTime": "2020-08-08T20:44:2",
"updateTime": "2020-08-08T20:44:3"
},
{
"name": "projects/..",
"fields": {
"15p3vl": {
"stringValue": "A2:2020;"
},
"2": {
"stringValue": "A6:..."
},
"t0w4yj": {
"stringValue": "A4:2020;"
},
"1": {
"stringValue": "A5:..."
}
},
"createTime": "2020-10-20T06:58:2",
"updateTime": "2020-10-20T06:58:2"
}
]
}
我希望結果是這樣的:
A1:Hello; A9:... A10:...
A2:2020; A6:... A4:2020; A5:...
uj5u.com熱心網友回復:
由于上次我沒有解釋得足夠多,這里再試一次。
implementation
uses
System.JSON;
procedure DoSomeJSONStuff(const jsonstr: string);
var
jo, fields: TJSONObject;
ja: TJSONArray;
jv: TJSONValue;
i: integer;
desiredstr: string;
begin
// 1.
jo := TJSONObject.ParseJSONValue(jsonstr) as TJSONObject;
if (jo <> nil) then begin
try
// 2.
ja := jo.GetValue('documents') as TJSONArray;
// 3.
for jv in ja do begin
fields := (jv as TJSONObject).GetValue('fields') as TJSONObject;
desiredstr := '';
// 4.
for i := 0 to fields.Count - 1 do begin
desiredstr := desiredstr (fields.Pairs[i].JsonValue as TJSONObject).GetValue('stringValue').Value;
end;
ShowMessage(desiredstr);
end;
finally
// 5.
jo.Free;
end;
end;
end;
In
jsonstr是您的 JSON 作為字串。隨著TJSONObject.ParseJSONValue您可以分析您的JSON,并獲得TJSONValue回來,如果它不會失敗。否則值為nil,因此檢查variable <> nil。由于TJSONObject派生自TJSONValue,因此在這種情況下可以簡單地顯式轉換。幾乎所有內容都源自TJSONValueDelphi JSON 框架。如果你想檢查它TJSONValue是否真的是你想要的 JSON 容器,你可以這樣做:var jv: TJSONValue; jo: TJSONObject; begin jv := TJSONObject.ParseJSONValue(jsonstr); if jv is TJSONObject then begin jo := (jv as TJSONObject); // code here end else raise Exception.Create('Unexpected container - expected: TJSONObject');下一步是
documents在您的 JSON 中獲取 。它的值是一個陣列。如果您不確定可以使用的結構,TryGetValue而不是GetValue. 您可以再次檢查回傳的值是否實際上是TJSONArraywithvariable is TJSONArray。我假設你的結構總是一樣的。現在我們用一個簡單的
for in回圈遍歷陣列。由于您的元素名稱
fields沒有“靜態”名稱,我們按計數遍歷欄位。我們得到TJSONValue并將其轉換為TJSONObject. 對于TJSONObject我們獲取stringValuesGetValue('stringValue').Value并將其連接到desirestr變數。只要您只參考它,您只需釋放“主”變數/容器。其他一切都只是一個
Pointer.
Edit #1: Hint about nil. Edit #2: Free memory.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315608.html
