
我曾有讲过Delphi操作JSON的方法,特别是这一篇【delphi】类和记录的 helpers(助手)。但是因为当时是主要介绍的是Delphi的Helper,大家可能并没注意到Delphi中JSON的简便操作方法。
早期Delphi并没有自己的JSON操作库,大家使用最多的是三方的SuperObject(名气很大),后来Delphi有了自己原生的JSON操作库(Delphi从版本XE6开始原生支持JSON操作),设计的非常完善,但是操作起来写的代码太多(谁用谁知道)。那么Delphi原生的JSON操作能否也像原来的SuperObject那样,书写代码量少又很优雅呢,当然可以。
直接上使用的代码,注意,要引用uJSON_Helper.pas这个单元,代码已经附在最后。细细品味,你一定有收获!
S[ ]:表示字符串
 I[ ]:表示整型数
 I64[ ]:表示int64
 D [ ]:表示日期
 A [ ]:表示数组
 O[ ]:表示TJSONObject对象
 B[ ]:表示逻辑值
Exists[ ]:判断节点是否存在
Delete[ ]:删除节点
使用Demo
uses
  uJSON_Helper;
var
  jo : TJSONObject;
  S  : string;
  sName : string;
  iAge  : Integer;
  bSex  : Boolean;
  sBirth: string;
  iSalary : Int64;
  sHobby1 : string;
begin
  jo := TJSONObject.Create;
  try
    //赋值操作
    jo.S['name'] := 'sensor';
    jo.I['age']  := 50;
    jo.B['sex']  := True;     //True表示男,False表示女
    jo.D['Birth']:= StrToDateTime('1970-02-13');   //日期型参数
    //子对象
    jo.O['workplace'] := TJSONObject.Create;
    jo.O['workplace'].S['address'] := '深圳市南山区科技园';
    jo.O['workplace'].S['tel'] := '0755-831788xx';
    jo.O['workplace'].I64['salary'] := 9223372036854775807;
    //数组
    jo.A['hobbies'] := TJSONArray.Create;
    jo.A['hobbies'].Add('乒乓球');
    jo.A['hobbies'].Add('下象棋');
    //S := jo.ToJSON;
    //S := jo.ToString;
    S := jo.Format;  //格式化成字符串,Delphi 10.3以后才有的格式化功能
    
    //读取操作
    sName := jo.S['name'];   //sensor
    iAge  := jo.I['age'];    //57
    bSex  := jo.B['sex'];    //True
    sBirth:= FormatDateTime('YYYY-MM-DD',jo.D['Birth']);  // 1970-02-13
    iSalary:= jo.O['workplace'].I64['salary'];   // 9223372036854775807
    sHobby1 := jo.A['hobbies'].Items[0].Value;    // 乒乓球
    //删除操作
    jo.DeletePair('sex');     // 删除性别 函数法
    jo.Delete['sex'];         // 删除性别 数组法
    S := jo.Format;
   
  finally
    jo.Free;
  end;
end;第一个S值
     {
             "name": "sensor",
             "age": 50,
             "Birth": 25612,
            "Sex": True,
             "workplace": {
                     "address": "深圳市南山区科技园",
                      "tel": "0755-831788xx",
                      "salary": 9223372036854775807
             },
             "hobbies": [
                 "乒乓球",
                 "下象棋"
             ]
         }
第二个S值
        {
             "name": "sensor",
             "age": 50,
             "Birth": 25612,
             "workplace": {
                     "address": "深圳市南山区科技园",
                      "tel": "0755-831788xx",
                      "salary": 9223372036854775807
             },
             "hobbies": [
                 "乒乓球",
                 "下象棋"
             ]
         }
uJSON_Helper.pas 完整代码
{**************************************
时间:2021-06-18
      2023-07-15 增加了删除函数
功能:1 实现delphi原生的JSON操作为 S[] 操作方式
作者:sensor QQ:910731685
}
unit uJSON_Helper;
interface
uses
  //System.Classes,
  //System.Types,
  //System.DateUtil,
  //System.Generics.Collections,
  //System.SysUtils,
  System.JSON;
type
  TJSONObjectHelper = class helper for TJSONObject
    private
       function  Get_ValueS(PairName : string) : string;
       procedure Set_ValueS(PairName,PairValue : string);
       function  Get_ValueI(PairName : string) : Integer;
       procedure Set_ValueI(PairName : string; PairValue : Integer);
       function  Get_ValueI64(PairName : string) : Int64;
       procedure Set_ValueI64(PairName : string; PairValue : Int64);
       function  Get_ValueD(PairName : string) : TDateTime;
       procedure Set_ValueD(PairName : string; PairValue : TDateTime);
       function  Get_ValueB(PairName : string) : Boolean;
       procedure Set_ValueB(PairName : string; PairValue : Boolean);
       function  Get_ValueA(PairName : string) : TJSONArray;
       procedure Set_ValueA(PairName : string; PairValue : TJSONArray);
       function  Get_ValueO(PairName : string) : TJSONObject;
       procedure Set_ValueO(PairName : string; PairValue : TJSONObject);
       //2023-07-15
       function  Get_ValueExists(PairName : string) : Boolean;
       function  Get_ValueDelete(PairName : string) : Boolean;
    public
      //判断某个字段是否存在
      function PairExists(PairName : string) : Boolean;
      function DeletePair(PairName : string) : Boolean;  //删除某个节点,如果节点存在则返回True,否则返回False,但执行命令后,肯定节点不存在了。
      //定义字段读取函数
      property S[PairName : string] : string      read Get_ValueS   write Set_ValueS;
      property I[PairName : string] : integer     read Get_ValueI   write Set_ValueI;
      property I64[PairName : string] : Int64     read Get_ValueI64 write Set_ValueI64;
      property D[PairName : string] : TDateTime   read Get_ValueD   write Set_ValueD;
      property B[PairName : string] : Boolean     read Get_ValueB   write Set_ValueB;
      property A[PairName : string] : TJSONArray  read Get_ValueA   write Set_ValueA;
      property O[PairName : string] : TJSONObject read Get_ValueO   write Set_ValueO;
      //2023-07-15 增加
      property Exists[PairName : string] : Boolean  read Get_ValueExists;   //只读属性
      property Delete[PairName : string] : Boolean  read Get_ValueDelete;   //删除某个节点,如果节点存在则返回True,否则返回False,但执行命令后,肯定节点不存在了。
  end;
implementation
{ TJSONObjectHelper }
function TJSONObjectHelper.Get_ValueS(PairName: string): string;
var
  js : TJSONString;
begin
  if PairName = '' then  Exit;
  if Self.TryGetValue(PairName,js) then
     Result := js.Value
  else
     Result := '';
end;
function TJSONObjectHelper.PairExists(PairName: string): Boolean;
begin
  Result := Self.Values[PairName] <> nil;
end;
procedure TJSONObjectHelper.Set_ValueS(PairName, PairValue: string);
var
  js : TJSONString;
begin
  //1. 首先查找有没有该字段, 如果有,则直接删除
  if Self.TryGetValue(PairName,js) then
     begin
       Self.RemovePair(PairName).Free; //如果没有free,就会产生内存泄露
     end;
  //2. 然后在增加
  Self.AddPair(PairName, PairValue);
end;
function TJSONObjectHelper.Get_ValueI(PairName: string): Integer;
var
  ji : TJSONNumber;
begin
  if PairName = '' then  Exit(0);
  if Self.TryGetValue(PairName,ji) then
     Result := ji.AsInt
  else
     Result := 0;
end;
procedure TJSONObjectHelper.Set_ValueI(PairName: string; PairValue: Integer);
var
  jn : TJSONNumber;
begin
  //1. 首先查找有没有该字段, 如果有,则直接删除
  if Self.TryGetValue(PairName,jn) then
     Self.RemovePair(PairName).Free;
  //2. 然后在增加
  Self.AddPair(PairName, TJSONNumber.Create(PairValue));
end;
function TJSONObjectHelper.Get_ValueD(PairName: string): TDateTime;
var
  ji : TJSONNumber;
begin
  if PairName = '' then  Exit(0);
  if Self.TryGetValue(PairName,ji) then
     Result := ji.AsDouble
  else
     Result := 0;
end;
function TJSONObjectHelper.Get_ValueDelete(PairName: string): Boolean;
begin
  if not Self.PairExists(PairName) then Exit(False);
  Self.RemovePair(PairName).Free;
  Result := True;
end;
function TJSONObjectHelper.Get_ValueExists(PairName: string): Boolean;
begin
  Result := Self.Values[PairName] <> nil;
end;
procedure TJSONObjectHelper.Set_ValueD(PairName: string; PairValue: TDateTime);
var
  jn : TJSONNumber;
begin
  //1. 首先查找有没有该字段, 如果有,则直接删除
  if Self.TryGetValue(PairName,jn) then
     Self.RemovePair(PairName).Free;
  Self.AddPair(PairName, TJSONNumber.Create(PairValue));
end;
function TJSONObjectHelper.Get_ValueB(PairName: string): Boolean;
var
  jb : TJSONBool;
begin
  if PairName = '' then  Exit(False);
  if Self.TryGetValue(PairName,jb) then
     Result := jb.AsBoolean
  else
     Result := False;
end;
procedure TJSONObjectHelper.Set_ValueB(PairName: string; PairValue: Boolean);
var
  jb : TJSONBool;
begin
  //1. 首先查找有没有该字段, 如果有,则直接删除
  if Self.TryGetValue(PairName,jb) then
     Self.RemovePair(PairName).Free;
  Self.AddPair(PairName, TJSONBool.Create(PairValue));
end;
function TJSONObjectHelper.Get_ValueI64(PairName: string): Int64;
var
  ji : TJSONNumber;
begin
  if PairName = '' then  Exit(0);
  if Self.TryGetValue(PairName,ji) then
     Result := ji.AsInt64
  else
     Result := 0;
end;
procedure TJSONObjectHelper.Set_ValueI64(PairName: string; PairValue: Int64);
var
  jn : TJSONNumber;
begin
  //1. 首先查找有没有该字段, 如果有,则直接删除
  if Self.TryGetValue(PairName,jn) then
     Self.RemovePair(PairName).Free;
  Self.AddPair(PairName, TJSONNumber.Create(PairValue));
end;
function TJSONObjectHelper.DeletePair(PairName: string): Boolean;
begin
  if not Self.PairExists(PairName) then Exit(False);
  Self.RemovePair(PairName).Free;
  Result := True;
end;
function TJSONObjectHelper.Get_ValueA(PairName: string): TJSONArray;
begin
  if PairName = '' then  Exit(nil);
  Self.TryGetValue(PairName,Result);
end;
procedure TJSONObjectHelper.Set_ValueA(PairName: string; PairValue: TJSONArray);
var
  ja : TJSONArray;
begin
  //1. 首先查找有没有该字段, 如果有,则直接删除
  if Self.TryGetValue(PairName,ja) then
     Self.RemovePair(PairName).Free;
  Self.AddPair(PairName, PairValue);
end;
function TJSONObjectHelper.Get_ValueO(PairName: string): TJSONObject;
var
  jo : TJSONObject;
begin
  if PairName = '' then  Exit(nil);
  if Self.TryGetValue(PairName,jo) then
     Result := jo
  else
     Result := nil;
end;
procedure TJSONObjectHelper.Set_ValueO(PairName: string; PairValue: TJSONObject);
var
  jo : TJSONObject;
begin
  //1. 首先查找有没有该字段, 如果有,则直接删除
  if Self.TryGetValue(PairName,jo) then
     Self.RemovePair(PairName).Free;
  Self.AddPair(PairName, PairValue as TJSONObject);
end;
end.真正理解了,才知道操作的简便性!




![[QT编程系列-11]:C++图形用户界面编程,QT框架快速入门培训 - 5- QT主要控件与自定义控件](https://img-blog.csdnimg.cn/b3b4d4442f3e4ccfa859a1600abf64a7.png)














