function TForm1.获取商品(str: string): TItemArr; var MyJson:TJSONObject; Arr:TJSONArray; I:Integer; jsonvalue: Tjsonvalue; begin try MyJson:=TJSONObject.ParseJSONValue(Trim(str)) as TJSONObject; if MyJson.Count=4 then begin MyJson:=TJSONObject.ParseJSONValue(Trim(MyJson.Values['mods'].ToString)) as TJSONObject; MyJson:=TJSONObject.ParseJSONValue(Trim(MyJson.Values['itemlist'].ToString)) as TJSONObject; MyJson:=TJSONObject.ParseJSONValue(Trim(MyJson.Values['data'].ToString)) as TJSONObject; Arr:=MyJson.GetValue('auctions') as TJSONArray; SetLength(Result,Arr.Count); for I:=0 to Arr.Count - 1 do begin if (Arr.Get(I) as TJSONObject).TryGetValue('p4p',jsonvalue) then Result[I].p4p:=(Arr.Get(I) as TJSONObject).GetValue('p4p').Value; end; end; finally MyJson.Free; end; end;
调用这个函数: var MyItemArr:TItemArr; 商品字符串:string;
for I:=0 to 10 do begin 商品字符串:=获取商品字符串(I); //这里获取到的是一个json MyItemArr:=获取商品(商品字符串); //这里是写入数据库的代码 SetLength(MyItemArr,0); end;
try MyJson:=TJSONObject.ParseJSONValue(Trim(str)) as TJSONObject; if MyJson.Count=4 then begin MyJson:=TJSONObject.ParseJSONValue(Trim(MyJson.Values['mods'].ToString)) as TJSONObject; MyJson:=TJSONObject.ParseJSONValue(Trim(MyJson.Values['itemlist'].ToString)) as TJSONObject; MyJson:=TJSONObject.ParseJSONValue(Trim(MyJson.Values['data'].ToString)) as TJSONObject; Arr:=MyJson.GetValue('auctions') as TJSONArray; SetLength(Result,Arr.Count); for I:=0 to Arr.Count - 1 do begin if (Arr.Get(I) as TJSONObject).TryGetValue('p4p',jsonvalue) then Result[I].p4p:=(Arr.Get(I) as TJSONObject).GetValue('p4p').Value; end; end; finally MyJson.Free; end; 不内存泄露才怪 TJSONObject.ParseJSONValue 每次都是返回一个新的json对象,你只释放了一个
----------------------------------------------
-
var JsonObject: TJSONObject; begin JsonObject := TJSONObject.ParseJSONValue(JSON) as TJSONObject; try if JsonObject <> nil then begin ShowMessage(DateTimeToStr(JsonObject.GetValue<TDateTime>('o.1234567890.last use date'))); // 2010-10-17 1:23:20 ShowMessage(JsonObject.GetValue<string>('Data.Index2')); // 1 ShowMessage(JsonObject.GetValue<string>('a[0].name')); // iPhone 8s