Delphi下操作JSon,在Delphi7的时候,有各种各样的第三方组件,但是一直没尝试过。因为用不到。后来Delphi开始在XE系列的某个版本官方地支持JSON,并且这个时候,用Delphi来写Android也感受到了方便。 早些时候,习惯了用NativeExcel在Delphi下操作二维结构的数据,尤其NativeExcel有个好处,当创建了Excel的Book之后,只要不保存它,它就一直可以在内存里操作,并且配合自己添加的索引或者使用TStringList可以实现Excel式的排序。这要比SQLite方便:无需实际写文件,也不用劳烦Helper之类,功能肯定差了些。 可惜NativeExcel不能用在Android下面。那么简单的键-值对的数据结构,显然是JSon强项了。到DelphiTop找了两个页面,发现已经讲的很细腻了,趁值班试验一下,很容易竟然学会。有时间时,可以搞一个纯文件名单的点名册之类的东西了。 ……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;//随机数种子,产生不重复随机数 m_Object := TJSONObject.Create; try // JSON数组 m_JsonArray := TJSONArray.Create; // 数组成员 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('次数', TJSONNumber.Create(InttoStr(score))); m_JsonArray.Add(m_Json1); //键-值对,然后放在数组里,最后把数组放在对象里 //在JSon里,就是层次 // m_Json1.Free; // Free了数据就没了 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数组 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 > 《待分类》