如何在德尔福解析这种类型的JSON数据?



如何在德尔福中解析以下 Json?

这是我的第一篇文章,在问这个问题之前,我已经尽可能多地搜索了, 因此,如果我以任何方式错误地发布,请告诉我。

我想在"记录"数组中获取"name_of_centre"的值

感谢您的任何帮助。

procedure TForm1.Button1Click(Sender: TObject);
var
i : integer;
jsonRoot: TJSONValue;
jsonObj: TJSONObject;
jsonArr: TJSONArray;
begin
jsonRoot := TJSONObject.ParseJSONValue(memo2.Lines.text);
try
jsonObj := jsonRoot as TJSONObject;
jsonObj := jsonObj.GetValue('result') as TJSONObject;
jsonArr := jsonObj.GetValue('records') as TJSONArray;
showmessage( jsonArr.Count.ToString );  // works ok
for i := 0 to jsonArr.Count - 1 do
begin
jsonObj := jsonArr.Items[i] as TJSONObject;
showmessage( jsonObj.GetValue('name_of_centre').Value );   // error here
end;
finally
jsonRoot.Free;
end;
end;

我已退房 德尔福解析具有多种数组类型的 Json?

如何在西雅图德尔福 10 中解析此 json 数据? (尤其是这个(

以及其他一些链接...但 JSON 格式似乎不同。

有什么建议吗?

{
"help": "testing",
"success": true,
"result": {
"resource_id": "data_resource",
"fields": [
{
"type": "int4",
"id": "_id"
},
{
"type": "text",
"id": "name_of_centre"
},
{
"type": "text",
"id": "location_of_centre"
},
{
"type": "text",
"id": "type_of_centre"
},
{
"type": "text",
"id": "owner"
},
{
"type": "numeric",
"id": "no_of_outlets"
},
{
"type": "numeric",
"id": "no_of_branches"
}
],
"records": [
{
"location_of_centre": "Kings Road",
"no_of_outlets": "12",
"no_of_branches": "0",
"name_of_centre": "Kings Road Centre",
"type_of_centre": "HC",
"owner": "Private",
"_id": 1
},
{
"location_of_centre": "Queens",
"no_of_outlets": "14",
"no_of_branches": "1",
"name_of_centre": "Queens Centre",
"type_of_centre": "HC",
"owner": "Public",
"_id": 2
}
],
"_links": {
"start": "ignore",
"next": "ignore2"
},
"limit": 2,
"total": 10
}
}

感谢您的众多回复。

奥利维尔:我已经在这个修改后的代码中包含了这个错误。

彼得:我试过使用 jsonRoot.GetValue('result.records[0].name_of_centre'( 它确实给了我name_of_centre的价值。 良好的开端。 但是我希望让这段代码给我 Array 中的项目数,我迭代数组,而不是硬代码。谢谢。

雷米:奇怪的是,它今天有效。 它不会获得无效的类型转换 at showmessage( jsonObj.GetValue('name_of_centre'(.值 (;

fpiette : 我使用德尔福 10.3 RIO。

感谢大家的回复。

是否需要使用 jsonRoot.Free; -- 我在 stackoverflow.com 上的帖子中看到了这一点...jsonObj.Free怎么样?

jsonRoot := TJSONObject.ParseJSONValue(memo2.Lines.text);
try
jsonObj := jsonRoot as TJSONObject;
jsonObj := jsonObj.GetValue('result') as TJSONObject;
showmessage( jsonObj.ToString );
jsonArr := jsonObj.GetValue('records') as TJSONArray;
showmessage( jsonArr.Count.ToString );
for i := 0 to jsonArr.Count - 1 do
begin
jsonObj := jsonArr.Items[i] as TJSONObject;
if jsonObj .GetValue('name_of_centre').Value = null then
showmessage('null');

以前有一个无效的类型转换 showmessage( jsonObj.GetValue('name_of_centre'(.值 (; 结束; 最后 jsonRoot.Free; 结束;

最新更新