Delphi Json
作者:互联网
{ "班级1": { "classid": "101", "teacher": "Lee", "age": 25, "books": [ "book1", "book2", "book3" ] }, "班级2": { "classid": "102", "teacher": "Lee", "age": 25, "books": [ "book1", "book2", "book3" ] }, "班级3": { "classid": "103", "teacher": "Lee", "age": 25, "books": [ "book1", "book2", "book3" ] }, "班级4": { "classid": "104", "teacher": "Lee", "age": 25, "books": [ "book1", "book2", "book3" ] }, "班级5": { "classid": "105", "teacher": "Lee", "age": 25, "books": [ "book1", "book2", "book3" ] } }View Code
var i,j: Integer; jo: TJSONObject; root,root2: TJSONObject; jArr: TJSONArray; sKey,sVal: string; aPair: TJSONPair; aItem: TJsonValue; begin jo := TJSONObject.Create; try for i := 1 to 5 do begin jo.AddPair(Format('班级%d',[i]) ,TJSONObject.Create .AddPair('classid',Format('10%d',[i])) .AddPair('teacher','Lee') .AddPair('age',TJSONNumber.Create(25)) .AddPair('books',TJSONArray.Create .add('book1').add('book2').add('book3')) ); end; FJsonStr := jo.ToString; Memo1.Text := JSON_Format(jo.ToString); finally jo.Free; end; //Parse Json root := TJSONObject.ParseJSONValue(FJsonStr) as TJSONObject; if root <> nil then try //for i := 0 to root.Size - 1 do for i := 0 to root.Count - 1 do //同上 begin sKey := root.Get(i).JsonString.value; sVal := root.Get(i).JsonValue.toString; addLog('[%d] Key:%s,Val:%s',[i,sKey,sVal]); //root2 := root.Get(i).JsonValue as TJSONObject; root2 := root.GetValue(sKey) as TJSONObject; //同上 sKey := root2.Get(0).JsonString.value; //sVal := root2.Get(0).JsonValue.toString; sVal := root2.GetValue(sKey).ToString; addLog('[root2[0]] Key:%s,Val:%s',[sKey,sVal]); jArr := root2.GetValue('books') as TJSONArray; for j := 0 to jArr.Size - 1 do begin //addLog('Arr%d:%s',[j,jArr.Items[j].ToString]); //带双引号 addLog('Arr%d:%s',[j,jArr.Items[j].Value]); //不带双引号 end; end; finally root.Free; end; // Update root:= TJSONObject.ParseJSONValue(Trim(FJsonStr)) as TJSONObject; if root <> nil then try for i := 0 to Root.Count-1 do begin sKey := Root.Get(i).JsonString.value; sVal := Root.Get(i).JsonValue.toString; Root2:= Root.GetValue(sKey) as TJSONObject; //aPair:= Root2.Get(0);// aPair:= Root2.Get('classid'); //ok aItem := TJSONString.Create('New'+IntToStr(i)); aPair.JsonValue := aItem; end; FJsonStr := root.ToString; addLog(JSON_Format(FJsonStr)); finally root.Free; end; // Remove root:= TJSONObject.ParseJSONValue(Trim(FJsonStr)) as TJSONObject; if root <> nil then try for i := 0 to Root.Count-1 do begin sKey := Root.Get(0).JsonString.value; root.RemovePair(sKey).Free; addLog('Remove: ' + sKey); end; finally root.Free; end; end;View Code
标签:end,Get,Delphi,Json,TJSONObject,sKey,root,root2 来源: https://www.cnblogs.com/Jekhn/p/16388245.html