|
Delphi下操作JSon,在Delphi7的時候,有各種各樣的第三方組件,但是一直沒嘗試過。因為用不到。后來Delphi開始在XE系列的某個版本官方地支持JSON,并且這個時候,用Delphi來寫Android也感受到了方便。 早些時候,習慣了用NativeExcel在Delphi下操作二維結構的數(shù)據(jù),尤其NativeExcel有個好處,當創(chuàng)建了Excel的Book之后,只要不保存它,它就一直可以在內(nèi)存里操作,并且配合自己添加的索引或者使用TStringList可以實現(xiàn)Excel式的排序。這要比SQLite方便:無需實際寫文件,也不用勞煩Helper之類,功能肯定差了些。 可惜NativeExcel不能用在Android下面。那么簡單的鍵-值對的數(shù)據(jù)結構,顯然是JSon強項了。到DelphiTop找了兩個頁面,發(fā)現(xiàn)已經(jīng)講的很細膩了,趁值班試驗一下,很容易竟然學會。有時間時,可以搞一個純文件名單的點名冊之類的東西了。
……System.JSON, System.Math, Vcl.StdCtrls; …… procedure TForm1.Button1Click(Sender: TObject); var m_Object, m_Json1: TJSONObject; m_JsonArray: TJSONArray; i, score: Integer; begin Randomize;//隨機數(shù)種子,產(chǎn)生不重復隨機數(shù) m_Object := TJSONObject.Create; try // JSON數(shù)組 m_JsonArray := TJSONArray.Create; // 數(shù)組成員 for i := 1 to 40 do begin m_Json1 := TJSONObject.Create; score := RandomRange(1, 19); m_Json1.AddPair('姓名', TJSONString.Create('張' + InttoStr(i))); m_Json1.AddPair('次數(shù)', TJSONNumber.Create(InttoStr(score))); m_JsonArray.Add(m_Json1); //鍵-值對,然后放在數(shù)組里,最后把數(shù)組放在對象里 //在JSon里,就是層次 // m_Json1.Free; // Free了數(shù)據(jù)就沒了 end; // JSON對象 m_Object.AddPair('12班', m_JsonArray); // 輸出 Memo1.Lines.Clear; Memo1.Lines.Add(m_Object.ToString); finally m_Object.Free; end; end; procedure TForm1.Button2Click(Sender: TObject); var i:Integer; begin var jo: TJSONObject:=TJSONObject.ParseJSONValue(Memo1.Text) as TJSONObject; //edit1.Text:=inttostr(jo.Count); Edit1.Text:=jo.GetValue('12班').ToString; //Edit1.Text:=StringReplace(Edit1.Text,'[','',[rfReplaceAll]); //Edit1.Text:=StringReplace(Edit1.Text,']','',[rfReplaceAll]); var ja: TJSONArray := TJSONArray(jo.GetValue('12班')); // json數(shù)組 ShowMessage(IntToStr(ja.Count)); for i := 0 to 2 do begin //ja.Count-1,只試驗前3個 ShowMessage(ja.Items[i].ToString); var jo1: TJSONObject := TJSONObject.ParseJSONValue(ja.Items[i].ToString) as TJSONObject; //從字符串生成JSON ShowMessage(jo1.Values['姓名'].ToString); jo1.free; end; jo.Free; end; end.
微信公號里面寫代碼,格式真的太糟糕了。 |
|
|
來自: 新用戶5228KeDY > 《待分類》