gpt4 book ai didi

json - 如何在Delphi Xe4中读取相当简单的JSON文件?

转载 作者:行者123 更新时间:2023-12-03 15:18:22 27 4
gpt4 key购买 nike

我已经为此苦苦挣扎了一段时间,做一些简单的事情似乎花了太长时间。

我有一个这样的文件:

[
{
"FirstName": "Oleg",
"Surname": "Buckley"
},
{
"FirstName": "Amery",
"Surname": "Mcmillan"
},
{
"FirstName": "Denton",
"Surname": "Burnett"
....

我希望能够将它们读入我的程序中。到目前为止,我已经完成了这个相当小的功能:

function GetGeneratedNames: TArray<string>;
var fileName: TFileName;
JSONValue, jv: TJSONValue;
JSONArray: TJSONArray;
jo: TJSONObject;
pair: TJSONPair;
begin
result := nil;
filename := ExePath + 'Names.json';
JSONValue := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(TFile.ReadAllText(filename)), 0);
if JSONValue is TJSONArray then begin
for jv in (JSONValue as TJSONArray) do begin
if jv is TJSONObject then begin
jo := jv as TJSONObject;
for pair in jo do begin
Append(result, jo.Value);
end;
end;
end;
end;
end{ GetGeneratedNames};

问题是,它返回一个空白字符串数组。谁能指出我正确的方向?

TIA标记

最佳答案

// XE5- version
uses System.SysUtils, Data.DBXJSON, System.IOUtils;

function GetGeneratedNames: TArray<string>;
var
fileName: TFileName;
JSONValue, jv: TJSONValue;
begin
fileName := TPath.Combine(ExePath, 'Names.json');
JSONValue := TJSONObject.ParseJSONValue(TFile.ReadAllText(fileName));
try
if JSONValue is TJSONArray then
begin
for jv in TJSONArray(JSONValue) do
begin
Append(Result, (jv as TJSONObject).Get('FirstName').JSONValue.Value);
Append(Result, (jv as TJSONObject).Get('Surname').JSONValue.Value);
end;
end;
finally
JSONValue.Free;
end;
end { GetGeneratedNames };

// XE6+ version
uses System.SysUtils, System.JSON, System.IOUtils;

function GetGeneratedNames: TArray<string>;
var
fileName: TFileName;
JSONValue, jv: TJSONValue;
begin
fileName := TPath.Combine(ExePath, 'Names.json');
JSONValue := TJSONObject.ParseJSONValue(TFile.ReadAllText(fileName));
try
if JSONValue is TJSONArray then
begin
for jv in TJSONArray(JSONValue) do
begin
Append(Result, jv.GetValue<string>('FirstName'));
Append(Result, jv.GetValue<string>('Surname'));
end;
end;
finally
JSONValue.Free;
end;
end { GetGeneratedNames };

关于json - 如何在Delphi Xe4中读取相当简单的JSON文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24466576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com