javascript
JSON 之 SuperObject(11): TSuperTableString、TSuperAvlEntry
通過 ISuperObject.AsObject 可獲取一個(gè) TSuperTableString 對象.
TSuperTableString 的常用屬性: count、GetNames、GetValues
varjo: ISuperObject;jts: TSuperTableString; beginjo := SO('{A:1, B:2, C:3, D:{x:4, y:5, z:6}}');jts := jo.AsObject;ShowMessage(IntToStr(jts.count));? ? // 4ShowMessage(jts.GetNames.AsString);? // ["D","C","B","A"]ShowMessage(jts.GetValues.AsString); // [{"z":6,"y":5,"x":4},3,2,1]jts := jo['D'].AsObject;ShowMessage(IntToStr(jts.count));? ? // 3ShowMessage(jts.GetNames.AsString);? // ["z","y","x"]ShowMessage(jts.GetValues.AsString); // [6,5,4] end;
JSON 本質(zhì)就是一個(gè)二叉樹(SuperObject 支持 32 層深度, 足夠了);
二叉樹的每個(gè)節(jié)點(diǎn)主要表示一個(gè) Name:Value; 其中的 Name 是字符串, Value 可能是個(gè)字符串、整數(shù)、數(shù)組或另一個(gè) ISuperObject, 所以 Value 的類型只能是 ISuperObject.
描述這個(gè)節(jié)點(diǎn)的類是 TSuperAvlEntry, 我們可以從一個(gè) TSuperTableString 中枚舉出當(dāng)前層及的每個(gè) TSuperAvlEntry.
varjo, io: ISuperObject;item: TSuperAvlEntry; beginjo := SO('{A:1, B:2, C:3, D:{x:4, y:5, z:6}}');{從 TSuperTableString(這里是用 jo.AsObject 獲取)中枚舉 TSuperAvlEntry}Memo1.Clear;for item in jo.AsObject doMemo1.Lines.Add(Format('Name: %s; Value: %s', [item.Name, item.Value.AsString]));{直接從 ISuperObject 中枚舉 "子ISuperObject"}Memo1.Lines.Add(EmptyStr);for io in jo doMemo1.Lines.Add(Format('Value: %s', [io.AsString])); end;
上面的遍歷都沒有深入下去, 要徹底深入地遍歷需要寫回調(diào)函數(shù).
下面寫了兩個(gè)回調(diào)函數(shù), 第一個(gè)沒有考慮數(shù)組中的對象:
uses SuperObject;//使用回調(diào)的遍歷過程之一: 沒考慮數(shù)組中的對象 procedure Proc1(jo: ISuperObject; var List: TStrings); varitem: TSuperAvlEntry; beginfor item in jo.AsObject doif item.Value.DataType = stObject thenProc1(item.Value, List) {如果是對象就回調(diào)}else {不是對象就添加到列表}List.Add(Format('%s : %s', [item.Name, item.Value.AsString])); end;//使用回調(diào)的遍歷過程之二: procedure Proc2(jo: ISuperObject; var List: TStrings); vari: Integer;item: TSuperAvlEntry; beginfor item in jo.AsObject dobeginif item.Value.DataType = stObject thenProc2(item.Value, List) {如果是對象就回調(diào)}else begin {不是對象就添加到列表}List.Add(Format('%s : %s', [item.Name, item.Value.AsString]));if item.Value.DataType = stArray then begin {如果是數(shù)組, 看看里面是不是有對象}for i := 0 to item.Value.AsArray.Length - 1 doif item.Value.AsArray[i].DataType = stObject thenProc2(item.Value.AsArray[i], List); {如果是對象就再回調(diào)}end;end;end; end;//調(diào)用測試 procedure TForm1.Button1Click(Sender: TObject); varjo: ISuperObject;List: TStrings; beginjo := SO('{A:1, B:2, C:3, D:[4, 5, {X:6}, {Y:[7,8,{m:9}]}]}');List := TStringList.Create;Proc1(jo, List);ShowMessage(List.Text);List.Clear;Proc2(jo, List);ShowMessage(List.Text);List.Free; end;
轉(zhuǎn)載于:https://www.cnblogs.com/cpprun/p/4787979.html
總結(jié)
以上是生活随笔為你收集整理的JSON 之 SuperObject(11): TSuperTableString、TSuperAvlEntry的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 女人梦到姜是什么意思
- 下一篇: 由于可能不会将凭据发送到远程计算机,因此