AI摘要
本文介绍了如何使用Delphi XE软件解析JSON数据并将其保存到数据库。首先,通过程序获取WEB返回的JSON字符串,然后使用TJSONObject.ParseJSONValue方法解析JSON对象。接着,分别解析code、message、ttl等元素的值,以及data元素中的list数组和is_maintain元素。最后,遍历list数组并解析每个元素的值,将所需数据保存到数据库。文章提供了详细的代码示例,方便读者理解和学习。
本文介绍了如何使用Delphi X
这是一段WEB返回的Json串
我想通过程序将这些数据保存到数据库
procedure TForm1.rzbtbtn_getgiftClick(Sender: TObject);
var
jsonStr: string;
jsonObj, dataObj,itemObj: TJSONObject;
listArr: TJSONArray;
i: Integer;
begin
Fhtmlsrc:=mmo1.Lines.Text;
jsonStr := Fhtmlsrc;
jsonObj := TJSONObject.ParseJSONValue(jsonStr) as TJSONObject;
try
// 解析code、message和ttl元素的值
mmo1.Lines.Add('code = '+ jsonObj.GetValue('code').Value);
mmo1.Lines.Add('message = '+jsonObj.GetValue('message').Value);
mmo1.Lines.Add('ttl = '+ jsonObj.GetValue('ttl').Value);
// 解析data元素中的list数组和is_maintain元素
dataObj := jsonObj.GetValue('data') as TJSONObject;
listArr := dataObj.GetValue('list') as TJSONArray;
// 遍历list数组并解析每个元素的值
for i :=0 to listArr.Count - 1 do
begin
jsonStr:=listArr.Items[i].ToJSON;
itemObj := TJSONObject.ParseJSONValue(jsonStr) as TJSONObject;
mmo1.Lines.Add('-----------');
mmo1.Lines.Add('level = '+ itemObj.GetValue('level').Value);
mmo1.Lines.Add('uid = '+ itemObj.GetValue('uid').Value);
mmo1.Lines.Add('contribution = '+ itemObj.GetValue('contribution').Value);
mmo1.Lines.Add('name = '+ itemObj.GetValue('name').Value);
mmo1.Lines.Add('icon = '+ itemObj.GetValue('icon').Value);
end;
// 解析is_maintain元素的值
mmo1.Lines.Add('is_maintain = '+dataObj.GetValue('is_maintain').Value);
finally
jsonObj.Free;
end;
end;