我有这个json,我想得到fname值。我怎么能用德尔菲做这件事?
{
"root":[
{
"customers":[
{
"fname":"George Makris",
"Age":12
}
]
}
]
}我现在正在做的事情是这样的,但我不认为这是一条必经之路
procedure TForm1.Button1Click(Sender: TObject);
var s,json:string;
myObj:TJSONObject;
myarr:TJSONArray;
begin
json:='{"root":[{"customers":[ { "fname":"George Makris","Age":12}]}]}';
myObj := TJSONObject.ParseJSONValue(json) as TJSONObject;
myarr := myObj.GetValue('root') as TJSONArray;
myObj := myarr.Items[0] as TJSONObject;
myarr := myObj.GetValue('customers') as TJSONArray;
myObj := myarr.Items[0] as TJSONObject;
s := myObj.GetValue('fname').value;
showmessage(s);
end;发布于 2018-11-01 11:26:39
您的示例已接近,但会泄漏内存,特别是ParseJSONValue的结果。
我更喜欢使用TryGetValue来验证内容是否存在。它还根据所使用的参数推断类型。这里有一个两者都没有泄漏的例子。
procedure TForm3.btnStartClick(Sender: TObject);
var
s, JSON: string;
jo: TJSONObject;
myarr: TJSONArray;
begin
JSON := '{"root":[{"customers":[ { "fname":"George Makris","Age":12}]}]}';
jo := TJSONObject.ParseJSONValue(JSON) as TJSONObject;
try
if jo.TryGetValue('root', myarr) and (myarr.Count > 0) then
if myarr.Items[0].TryGetValue('customers', myarr) and (myarr.Count > 0) then
if myarr.Items[0].TryGetValue('fname', s) then
showmessage(s);
finally
jo.Free;
end;
end;https://stackoverflow.com/questions/53098385
复制相似问题