加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 09:07:42 所属栏目:大数据 来源:网络整理
导读:我一直在努力解决这个问题,做一些简单的事情似乎花了太长时间. 我有这样一个文件: [ { "FirstName": "Oleg","Surname": "Buckley" },{ "FirstName": "Amery","Surname": "Mcmillan" },{ "FirstName": "Denton","Surname": "Burnett".... 我希望能够将它们读
我一直在努力解决这个问题,做一些简单的事情似乎花了太长时间.

我有这样一个文件:

[
 {
  "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,jv.GetValue<string>('FirstName'));
        Append(Result,jv.GetValue<string>('Surname'));
      end;
    end;
  finally
    JSONValue.Free;
  end;
end { GetGeneratedNames };

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读