Delphi XE JSON[3] 解析資料
阿新 • • 發佈:2022-03-20
{該文首發於部落格園 滔Roy,無須授權即可轉發,請自覺保留頭部申明}
Delphi XE JSON[3] 解析資料
1、解析單個文字
var JSONValue: TJSONValue; JSObject:TJSONObject; JValue:string; begin if Trim(Memo1.Text)='' then Exit; JSONValue:=TJSONObject.ParseJSONValue(Memo1.Text); //使用TJSONObject.ParseJSONValue讀取JSON資料 JSObject:=JSONValue as TJSONObject; //將JSONValue轉換為TJSONObject型別 if JSObject.TryGetValue(EditName.Text,JValue) then MemoValue.Text:=JValue; JSObject.Free; end;
2、解析資料(指定陣列)
var JSONValue: TJSONValue; JSObject:TJSONObject; JSONArr:TJSONArray; begin if Trim(Memo1.Text)='' then Exit; JSONValue:=TJSONObject.ParseJSONValue(Memo1.Text); //使用TJSONObject.ParseJSONValue讀取JSON資料 JSObject:=JSONValue as TJSONObject; //將JSONValue轉換為TJSONObject型別 if JSObject.TryGetValue(EditName.Text,JSONArr) then // JSONArr:=JSObject.GetValue(EditName.Text) as TJSONArray; MemoValue.Text:=JSONArr.ToString; JSObject.Free; end;
3、迴圈解析資料(指定陣列)
var JSONValue: TJSONValue; JSObject:TJSONObject; JSONArr:TJSONArray; i:Integer; JValue:string; begin if Trim(Memo1.Text)='' then Exit; MemoValue.Clear; JSONValue:=TJSONObject.ParseJSONValue(Memo1.Text); //使用TJSONObject.ParseJSONValue讀取JSON資料 JSObject:=JSONValue as TJSONObject; //將JSONValue轉換為TJSONObject型別 if JSObject.TryGetValue(EditName.Text,JSONArr) then // JSONArr:=JSObject.GetValue(EditName.Text) as TJSONArray; for i:=0 to JSONArr.Count-1 do begin if JSONArr.Items[i].TryGetValue('名稱',JValue) then MemoValue.Lines.Add( '名稱=' + JValue); if JSONArr.Items[i].TryGetValue('數量',JValue) then MemoValue.Lines.Add( '數量=' + JValue); if JSONArr.Items[i].TryGetValue('價格',JValue) then MemoValue.Lines.Add( '價格=' + JValue); end; JSObject.Free; end;
4、迴圈格式化(不指定陣列)
var
JSONValue: TJSONValue;
JSObject,JSObject1:TJSONObject;
JSONArr:TJSONArray;
i,j,k:Integer;
JName,JName1:string;
JValue,JValue1:TJSONValue;
begin
if Trim(Memo1.Text)='' then Exit;
MemoValue.Clear;
JSONValue:=TJSONObject.ParseJSONValue(Memo1.Text); //使用TJSONObject.ParseJSONValue讀取JSON資料
JSObject:=JSONValue as TJSONObject; //將JSONValue轉換為TJSONObject型別
//第一層
for i:=0 to JSObject.Count-1 do begin
JName:=JSObject.Get(i).JsonString.ToString;
JValue:=JSObject.Get(i).JsonValue;
MemoValue.Lines.Add(JName+'=');
if JValue is TJSONArray then begin //先判斷型別
JSONArr:=JSObject.Get(i).JsonValue as TJSONArray;
for j := 0 to JSONArr.Size-1 do begin
JSObject1:=JSONArr.Items[j] as TJSONObject;
for k := 0 to JSObject1.Count-1 do begin
JName1:=JSObject1.Get(k).JsonString.ToString;
JValue1:=JSObject1.Get(k).JsonValue;
MemoValue.Lines.Add(' '+JName1+'='+JValue1.ToString);
end;
end;
end else begin
MemoValue.Lines.Add(JValue.ToString);
end;
end;
JSObject.Free;
end;
建立時間:2022.03.20 更新時間: