1
0

rjson.pas 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. (*
  2. # Delphi JSON common operation encapsulation JSON数据读写封装
  3. - v0.9.1
  4. - 2024-09-05 by gale
  5. - https://github.com/higale/rjson
  6. ## Properties:
  7. - Items[Path] 路径读写,对Object和Array都有效
  8. a['x.y[2].z'] := 5;
  9. b['[3].ok'] := false;
  10. - Items[Index] 数组读写
  11. a[3][1] := 'hello';
  12. - Pairs[Index] 获取JSONObject下的键值对
  13. for var i := 0 to RJ.Count do
  14. begin
  15. Memo1.Lines.Add(RJ.Pairs[i].Key + '=' + RJ.Pairs[i].Format(0));
  16. end;
  17. - Count Object或Array包含条目数,其它类型返回0
  18. - Index 条目在Array中的索引值,不是数组数条目据返回-1
  19. - Key 如果是键值对数据,返回键值,否则返回空
  20. - Root 根数据接口
  21. - Path 值的路径
  22. - JSONValue 包含的TJSONValue值
  23. ## Methods
  24. - ToStr 转换为字符串,缺省为空
  25. var str: string;
  26. str := RJ['title'];
  27. str := RJ['title'].ToStr;
  28. str := RJ['title'].ToStr('没有标题');
  29. - ToInt 转换为整数,缺省为0
  30. var i: integer;
  31. i := RJ['num'];
  32. i := RJ['num'].ToInt;
  33. i := RJ['num'].ToInt(-1);
  34. - ToInt64 转换为64位整数,缺省为0
  35. var i64: Int64;
  36. i64 := RJ['num64'];
  37. i64 := RJ['num64'].ToInt64;
  38. i64 := RJ['num64'].ToInt64(-1);
  39. - ToFloat 转换为浮点数(使用 Extended),缺省为0.0
  40. var f: Extended;
  41. f := RJ['num'];
  42. f := RJ['num'].ToFloat;
  43. f := RJ['num'].ToFloat(100.0);
  44. - ToBool 转换为 Boolean,缺省为 False
  45. var b:Boolean;
  46. b := RJ['bool'];
  47. b := RJ['bool'].ToBool;
  48. b := RJ['bool'].ToBool(True);
  49. - RootIs<T: TJSONValue> 根是否是某种类型(TJSONObject、TJSONArray等)
  50. - ValueIs<T: TJSONValue> 当前值是否是某种类型(TJSONObject、TJSONArray等)
  51. - CloneJSONValue 克隆一份当前值,如果当前值不存在,则生成 TJSONNull
  52. - Reset 复位到出厂状态
  53. - Format 输出格式化好的JSON字符串
  54. str1 := RJ.Format(2); // 缩进2个空格(缺省4个)
  55. str2 := RJ.Format(0); // 压缩格式,无缩进无换行
  56. - ParseJSONValue 从字符串加载数据
  57. RJ.ParseJSONValue('{"a":1}');
  58. - LoadFromFile 从文件加载数据
  59. procedure LoadFromFile(
  60. const AFileName: string; // JSON文件名
  61. AUseBool: boolean = False; // 遇到JSON数据中的 true 或 false 时,是否创建 TJSONBool 类型的值
  62. ARaiseExc: boolean = False // 遇到无效的 JSON 数据时是否抛出异常
  63. );
  64. - SaveToFile 保存到文件
  65. procedure aveToFile(
  66. const AFileName: string; // 文件名
  67. AIndentation: Integer = 4; // 缩进空格数,0:不缩进不换行
  68. AWriteBOM: boolean = False; // 文件是否添加 BOM 标记
  69. ATrailingLineBreak: boolean = False // 是否在结尾添加一个空行
  70. );
  71. ## Example:
  72. procedure TFormMain.btnTestClick(Sender: TObject);
  73. var
  74. RJ, RJ1: TRJSON;
  75. fTemp: Extended;
  76. begin
  77. RJ['title'] := 'hello world! 你好,世界!';
  78. RJ['a.num'] := 1;
  79. RJ['a.hah'] := false;
  80. RJ['b[2]'] := 505;
  81. RJ['b[0]'] := 'first';
  82. RJ['good'] := True;
  83. RJ1 := RJ['c'];
  84. RJ1['c1'] := 1.1;
  85. RJ1['c2[2]'] := 2.33;
  86. with RJ['x'] do
  87. begin
  88. items[1] := 100;
  89. items[2] := '202';
  90. end;
  91. with RJ['y'] do
  92. begin
  93. items['ya'] := 'y1';
  94. items['yb'] := -2;;
  95. end;
  96. Memo1.Text := RJ.Format;
  97. Memo1.Lines.Add('-----------------------------------------------------------');
  98. fTemp := RJ['c.c2[3]'];
  99. Memo1.Lines.Add('fTemp:' + fTemp.ToString);
  100. fTemp := RJ['c.c3[3]'].ToFloat(-100);
  101. Memo1.Lines.Add('fTemp:' + fTemp.ToString);
  102. Memo1.Lines.Add(RJ['a.num'].ToStr('a.num not exist'));
  103. Memo1.Lines.Add(RJ['none'].ToFloat(-1).ToString);
  104. Memo1.Lines.Add(RJ['none.a3'].ToStr('none.a3 not exist'));
  105. RJ.SaveToFile('test.json', 0);
  106. end;
  107. procedure TFormMain.btnOpenClick(Sender: TObject);
  108. var
  109. RJ: TRJSON;
  110. strTmp: string;
  111. begin
  112. RJ.LoadFromFile('test.json');
  113. Memo1.Text := RJ.Format(8);
  114. Memo1.Lines.Add('-----------------------ROOT--------------------------');
  115. for var item in RJ do
  116. begin
  117. strTmp := Format('Index: %d Key: %s Value: %s',
  118. [item.Index, item.Key, item.Format(0)]);
  119. Memo1.Lines.Add(strTmp);
  120. end;
  121. Memo1.Lines.Add('-----------------------RJ[''a'']--------------------------');
  122. for var item in RJ['a'] do
  123. begin
  124. strTmp := Format('Index: %d Key: %s Value: %s',
  125. [item.Index, item.Key, item.Format(0)]);
  126. Memo1.Lines.Add(strTmp);
  127. end;
  128. Memo1.Lines.Add('-----------------------RJ[''b'']--------------------------');
  129. for var item in RJ['b'] do
  130. begin
  131. strTmp := Format('Index: %d Key: %s Value: %s',
  132. [item.Index, item.Key, item.Format(0)]);
  133. Memo1.Lines.Add(strTmp);
  134. end;
  135. Memo1.Lines.Add('-----------------------RJ[''c'']--------------------------');
  136. for var i := 0 to RJ['c'].Count - 1 do
  137. begin
  138. strTmp := Format('Index: %d Key: %s Value: %s',
  139. [RJ['c'].Pairs[i].Index, RJ['c'].Pairs[i].Key, RJ['c'].Pairs[i].Format(0)]);
  140. Memo1.Lines.Add(strTmp);
  141. end;
  142. end;
  143. *)
  144. unit rjson;
  145. interface
  146. uses
  147. System.IOUtils, System.Classes, System.SysUtils, System.StrUtils, System.JSON,
  148. System.Generics.Collections;
  149. type
  150. TJO = TJSONObject;
  151. TJA = TJSONArray;
  152. TJV = TJSONValue;
  153. TJSONValueType = type of TJSONValue;
  154. TRJSONEnumerator = class;
  155. { JSON root data interface }
  156. IRJSONRoot = interface
  157. function GetData: TJSONValue;
  158. procedure SetData(const AValue: TJSONValue);
  159. function ForceJV(AType: TJSONValueType): TJSONValue;
  160. property Data: TJSONValue read GetData write SetData;
  161. end;
  162. { JSON root data interface class }
  163. TRJSONRoot = class(TInterfacedObject, IRJSONRoot)
  164. private
  165. FData: TJSONValue;
  166. function GetData: TJSONValue;
  167. procedure SetData(const AValue: TJSONValue);
  168. function ForceJV(AType: TJSONValueType): TJSONValue;
  169. public
  170. constructor Create; overload;
  171. constructor Create(const AValue: TJSONValue); overload;
  172. destructor Destroy; override;
  173. end;
  174. { JSON data operation structure }
  175. TRJSON = record
  176. private
  177. FRoot: IRJSONRoot;
  178. FPath: string;
  179. function LinkPath(const ALeft, ARight: string): string;
  180. function GetJSONValue: TJSONValue; inline;
  181. function GetItems(const APath: string): TRJSON; overload;
  182. function GetItems(AIndex: Integer): TRJSON; overload; inline;
  183. function GetPairs(AIndex: Integer): TRJSON;
  184. procedure SetValue(const [ref] AValue: TRJSON);
  185. procedure SetItems(const APath: string; const [ref] AValue: TRJSON); overload;
  186. procedure SetItems(AIndex: Integer; const [ref] AValue: TRJSON); overload; inline;
  187. function GetCount: Integer;
  188. function GetIndex: Integer;
  189. function GetKey: string;
  190. public
  191. function GetEnumerator(): TRJSONEnumerator;
  192. class operator Initialize(out Dest: TRJSON);
  193. class operator Finalize(var Dest: TRJSON);
  194. class operator Assign(var Dest: TRJSON; const [ref] Src: TRJSON);
  195. class operator Implicit(const Value: string): TRJSON;
  196. class operator Implicit(const [ref] Value: TRJSON): string;
  197. class operator Implicit(Value: Integer): TRJSON;
  198. class operator Implicit(const [ref] Value: TRJSON): Integer;
  199. class operator Implicit(Value: Int64): TRJSON;
  200. class operator Implicit(const [ref] Value: TRJSON): Int64;
  201. class operator Implicit(Value: Extended): TRJSON;
  202. class operator Implicit(const [ref] Value: TRJSON): Extended;
  203. class operator Implicit(Value: boolean): TRJSON;
  204. class operator Implicit(const [ref] Value: TRJSON): boolean;
  205. class operator Implicit(const Value: TJSONValue): TRJSON;
  206. function ToStr(const ADefault: string = ''): string;
  207. function ToInt(ADefault: Integer = 0): Integer;
  208. function ToInt64(ADefault: Int64 = 0): Int64;
  209. function ToFloat(ADefault: Extended = 0.0): Extended;
  210. function ToBool(ADefault: boolean = False): boolean;
  211. property Items[const APath: string]: TRJSON read GetItems write SetItems; default;
  212. property Items[AIndex: Integer]: TRJSON read GetItems write SetItems; default;
  213. property Pairs[AIndex: Integer]: TRJSON read GetPairs;
  214. property Count: Integer read GetCount;
  215. property Index: Integer read GetIndex;
  216. property Key: string read GetKey;
  217. property Root: IRJSONRoot read FRoot;
  218. property Path: string read FPath;
  219. function RootIs<T: TJSONValue>: boolean;
  220. function ValueIs<T: TJSONValue>: boolean;
  221. property JSONValue: TJSONValue read GetJSONValue;
  222. function CloneJSONValue: TJSONValue;
  223. procedure Reset;
  224. function Format(Indentation: Integer = 4): string;
  225. procedure ParseJSONValue(const AData: string; AUseBool: boolean = False; ARaiseExc: boolean = False);
  226. procedure LoadFromFile(const AFileName: string; AUseBool: boolean = False; ARaiseExc: boolean = False);
  227. procedure SaveToFile(const AFileName: string; AIndentation: Integer = 4; AWriteBOM: boolean = False; ATrailingLineBreak: boolean = False);
  228. end;
  229. { Iterators }
  230. TRJSONEnumerator = class
  231. private
  232. FPData: ^TRJSON;
  233. FIndex: Integer;
  234. function GetCurrent: TRJSON;
  235. public
  236. constructor Create(const [ref] AData: TRJSON);
  237. function MoveNext: boolean;
  238. property Current: TRJSON read GetCurrent;
  239. end;
  240. implementation
  241. { ============================================================================ }
  242. { TRJSONRoot }
  243. constructor TRJSONRoot.Create;
  244. begin
  245. inherited;
  246. FData := nil;
  247. end;
  248. constructor TRJSONRoot.Create(const AValue: TJSONValue);
  249. begin
  250. inherited Create;
  251. FData := AValue;
  252. end;
  253. destructor TRJSONRoot.Destroy;
  254. begin
  255. FData.Free;
  256. inherited;
  257. end;
  258. function TRJSONRoot.GetData: TJSONValue;
  259. begin
  260. Result := FData;
  261. end;
  262. procedure TRJSONRoot.SetData(const AValue: TJSONValue);
  263. begin
  264. FData := AValue;
  265. end;
  266. function TRJSONRoot.ForceJV(AType: TJSONValueType): TJSONValue;
  267. begin
  268. if not(FData is AType) then
  269. begin
  270. FData.Free;
  271. FData := AType.Create;
  272. end;
  273. Result := FData;
  274. end;
  275. { TRJSONRoot }
  276. { ============================================================================ }
  277. { TJSONValueHelper }
  278. type
  279. TJSONValueHelper = class helper for TJSONValue
  280. private
  281. procedure ObjSetItem(const AName: string; const AValue: TJSONValue);
  282. procedure ArrFill<T: TJSONValue>(ACount: Integer);
  283. procedure ArrInsert(const AIndex: Integer; const AValue: TJSONValue);
  284. procedure ArrSetItem(AIndex: Integer; const AValue: TJSONValue);
  285. function ToType<T>(ADefault: T): T;
  286. function GetOrCreate<T: TJSONValue>(AName: string): T;
  287. procedure SetValue(const APath: string; const AValue: TJSONValue);
  288. end;
  289. procedure TJSONValueHelper.ObjSetItem(const AName: string; const AValue: TJSONValue);
  290. var
  291. pairTmp: TJSONPair;
  292. begin
  293. pairTmp := TJSONObject(self).Get(AName);
  294. if pairTmp = nil then
  295. TJSONObject(self).AddPair(AName, AValue)
  296. else
  297. pairTmp.JSONValue := AValue;
  298. end;
  299. procedure TJSONValueHelper.ArrFill<T>(ACount: Integer);
  300. begin
  301. for var j := TJSONArray(self).Count to ACount do
  302. TJSONArray(self).AddElement(T.Create);
  303. end;
  304. procedure TJSONValueHelper.ArrInsert(const AIndex: Integer; const AValue: TJSONValue);
  305. begin
  306. TJSONArray(self).AddElement(AValue);
  307. for var i := AIndex to TJSONArray(self).Count - 2 do
  308. TJSONArray(self).AddElement(TJSONArray(self).Remove(AIndex));
  309. end;
  310. procedure TJSONValueHelper.ArrSetItem(AIndex: Integer; const AValue: TJSONValue);
  311. begin
  312. ArrFill<TJSONNull>(AIndex - 1);
  313. if AIndex <= TJSONArray(self).Count - 1 then
  314. TJSONArray(self).Remove(AIndex).Free;
  315. ArrInsert(AIndex, AValue);
  316. end;
  317. procedure TJSONValueHelper.SetValue(const APath: string; const AValue: TJSONValue);
  318. var
  319. LParser: TJSONPathParser;
  320. preName: string;
  321. jv: TJSONValue;
  322. begin
  323. if APath.IsEmpty then
  324. raise Exception.Create('TJSONValueHelper.SetValue: path cannot be empty');
  325. jv := self;
  326. LParser := TJSONPathParser.Create(APath);
  327. LParser.NextToken;
  328. while true do
  329. begin
  330. preName := LParser.TokenName;
  331. LParser.NextToken;
  332. case LParser.Token of
  333. TJSONPathParser.TToken.Name:
  334. jv := jv.GetOrCreate<TJSONObject>(preName);
  335. TJSONPathParser.TToken.ArrayIndex:
  336. jv := jv.GetOrCreate<TJSONArray>(preName);
  337. TJSONPathParser.TToken.Eof:
  338. begin
  339. if jv is TJSONObject then
  340. jv.ObjSetItem(preName, AValue)
  341. else
  342. jv.ArrSetItem(preName.ToInteger, AValue);
  343. break;
  344. end;
  345. else
  346. raise Exception.Create('TJSONValueHelper.SetValue, LParser.Token Error!');
  347. end;
  348. end;
  349. end;
  350. function TJSONValueHelper.ToType<T>(ADefault: T): T;
  351. begin
  352. if self = nil then
  353. Exit(ADefault);
  354. try
  355. Result := AsType<T>;
  356. except
  357. Result := ADefault;
  358. end;
  359. end;
  360. function TJSONValueHelper.GetOrCreate<T>(AName: string): T;
  361. begin
  362. if self is TJSONObject then
  363. begin
  364. Result := T(TJSONObject(self).GetValue(AName));
  365. if not(Result is T) then
  366. begin
  367. Result := T.Create;
  368. ObjSetItem(AName, Result);
  369. end;
  370. end
  371. else if self is TJSONArray then
  372. begin
  373. ArrFill<TJSONNull>(AName.ToInteger);
  374. Result := T(TJSONArray(self).Items[AName.ToInteger]);
  375. if not(Result is T) then
  376. begin
  377. Result := T.Create;
  378. ArrSetItem(AName.ToInteger, Result);
  379. end;
  380. end
  381. else
  382. begin
  383. raise Exception.Create('GetOrCreate<T> Error, self must be TJO or TJA');
  384. end;
  385. end;
  386. { TJSONValueHelper }
  387. { ============================================================================ }
  388. { TRJSONEnumerator }
  389. constructor TRJSONEnumerator.Create(const [ref] AData: TRJSON);
  390. begin
  391. inherited Create;
  392. FPData := @AData;
  393. FIndex := -1;
  394. end;
  395. function TRJSONEnumerator.GetCurrent: TRJSON;
  396. var
  397. jvTmp: TJSONValue;
  398. begin
  399. Result.Reset;
  400. Result.FRoot := FPData^.FRoot;
  401. jvTmp := FPData^.GetJSONValue;
  402. if jvTmp is TJSONObject then
  403. begin
  404. if FPData^.FPath = '' then
  405. Result.FPath := TJSONObject(jvTmp).Pairs[FIndex].JsonString.Value
  406. else
  407. Result.FPath := FPData^.FPath + '.' + TJSONObject(jvTmp).Pairs[FIndex].JsonString.Value;
  408. end
  409. else if jvTmp is TJSONArray then
  410. begin
  411. Result.FPath := FPData^.FPath + '[' + FIndex.ToString + ']';
  412. end;
  413. end;
  414. function TRJSONEnumerator.MoveNext: boolean;
  415. begin
  416. Inc(FIndex);
  417. Exit(FIndex < FPData^.Count)
  418. end;
  419. { TRJSONEnumerator }
  420. { ============================================================================ }
  421. { TRJSON }
  422. function TRJSON.GetEnumerator(): TRJSONEnumerator;
  423. begin
  424. Result := TRJSONEnumerator.Create(self);
  425. end;
  426. class operator TRJSON.Initialize(out Dest: TRJSON);
  427. begin
  428. Dest.FRoot := TRJSONRoot.Create;
  429. Dest.FPath := '';
  430. end;
  431. class operator TRJSON.Finalize(var Dest: TRJSON);
  432. begin
  433. Dest.FRoot := nil;
  434. end;
  435. function TRJSON.LinkPath(const ALeft, ARight: string): string;
  436. begin
  437. if ALeft.IsEmpty then
  438. Result := ARight
  439. else if ARight.IsEmpty then
  440. Result := ALeft
  441. else if ARight.StartsWith('[') then
  442. Result := ALeft + ARight
  443. else
  444. Result := ALeft + '.' + ARight;
  445. end;
  446. function TRJSON.GetJSONValue: TJSONValue;
  447. begin
  448. Result := FRoot.Data.FindValue(FPath);
  449. end;
  450. function TRJSON.CloneJSONValue: TJSONValue;
  451. begin
  452. Result := GetJSONValue;
  453. if Result <> nil then
  454. Result := Result.Clone as TJSONValue
  455. else
  456. Result := TJSONNull.Create;
  457. end;
  458. class operator TRJSON.Assign(var Dest: TRJSON; const [ref] Src: TRJSON);
  459. begin
  460. if Dest.FPath.IsEmpty then
  461. begin
  462. Dest.FRoot := Src.FRoot;
  463. Dest.FPath := Src.FPath;
  464. end
  465. else
  466. begin
  467. Dest.SetValue(Src);
  468. end;
  469. end;
  470. class operator TRJSON.Implicit(const Value: string): TRJSON;
  471. begin
  472. Result.FRoot.Data := TJSONString.Create(Value);
  473. end;
  474. class operator TRJSON.Implicit(const [ref] Value: TRJSON): string;
  475. begin
  476. Result := Value.ToStr('');
  477. end;
  478. class operator TRJSON.Implicit(Value: Integer): TRJSON;
  479. begin
  480. Result.FRoot.Data := TJSONNumber.Create(Value);
  481. end;
  482. class operator TRJSON.Implicit(const [ref] Value: TRJSON): Integer;
  483. begin
  484. Result := Value.ToInt(0);
  485. end;
  486. class operator TRJSON.Implicit(Value: Int64): TRJSON;
  487. begin
  488. Result.FRoot.Data := TJSONNumber.Create(Value);
  489. end;
  490. class operator TRJSON.Implicit(const [ref] Value: TRJSON): Int64;
  491. begin
  492. Result := Value.ToInt64(0);
  493. end;
  494. class operator TRJSON.Implicit(Value: Extended): TRJSON;
  495. begin
  496. Result.FRoot.Data := TJSONNumber.Create(Value);
  497. end;
  498. class operator TRJSON.Implicit(const [ref] Value: TRJSON): Extended;
  499. begin
  500. Result := Value.ToFloat(0.0);
  501. end;
  502. class operator TRJSON.Implicit(Value: boolean): TRJSON;
  503. begin
  504. Result.FRoot.Data := TJSONBool.Create(Value);
  505. end;
  506. class operator TRJSON.Implicit(const [ref] Value: TRJSON): boolean;
  507. begin
  508. Result := Value.ToBool(False);
  509. end;
  510. class operator TRJSON.Implicit(const Value: TJSONValue): TRJSON;
  511. begin
  512. Result.FRoot.Data := Value;
  513. end;
  514. function TRJSON.ToStr(const ADefault: string): string;
  515. begin
  516. Result := FRoot.Data.FindValue(FPath).ToType<string>(ADefault);
  517. end;
  518. function TRJSON.ToInt(ADefault: Integer = 0): Integer;
  519. begin
  520. Result := FRoot.Data.FindValue(FPath).ToType<Integer>(ADefault);
  521. end;
  522. function TRJSON.ToInt64(ADefault: Int64 = 0): Int64;
  523. begin
  524. Result := FRoot.Data.FindValue(FPath).ToType<Int64>(ADefault);
  525. end;
  526. function TRJSON.ToFloat(ADefault: Extended = 0.0): Extended;
  527. begin
  528. Result := FRoot.Data.FindValue(FPath).ToType<Extended>(ADefault);
  529. end;
  530. function TRJSON.ToBool(ADefault: boolean = False): boolean;
  531. begin
  532. Result := FRoot.Data.FindValue(FPath).ToType<boolean>(ADefault);
  533. end;
  534. function TRJSON.GetItems(const APath: string): TRJSON;
  535. begin
  536. Result.FRoot := FRoot;
  537. Result.FPath := LinkPath(FPath, APath);
  538. end;
  539. function TRJSON.GetItems(AIndex: Integer): TRJSON;
  540. begin
  541. Result := GetItems('[' + AIndex.ToString + ']');
  542. end;
  543. function TRJSON.GetPairs(AIndex: Integer): TRJSON;
  544. var
  545. jvTmp: TJSONValue;
  546. begin
  547. jvTmp := GetJSONValue;
  548. if (jvTmp is TJSONObject) then
  549. Result := GetItems(TJSONObject(jvTmp).Pairs[AIndex].JsonString.Value);
  550. end;
  551. procedure TRJSON.SetValue(const [ref] AValue: TRJSON);
  552. var
  553. LValue: TJSONValue;
  554. begin
  555. if FPath.IsEmpty then
  556. raise Exception.Create(' TRJSON.SetValue: Path is empty');
  557. LValue := AValue.CloneJSONValue;
  558. try
  559. if FPath.StartsWith('[') then
  560. FRoot.ForceJV(TJSONArray).SetValue(FPath, LValue)
  561. else
  562. FRoot.ForceJV(TJSONObject).SetValue(FPath, LValue);
  563. except
  564. on E: Exception do
  565. begin
  566. LValue.Free;
  567. raise Exception.Create(E.message);
  568. end;
  569. end;
  570. end;
  571. procedure TRJSON.SetItems(const APath: string; const [ref] AValue: TRJSON);
  572. var
  573. tmp: TRJSON;
  574. begin
  575. tmp.FRoot := FRoot;
  576. tmp.FPath := LinkPath(FPath, APath);
  577. tmp.SetValue(AValue)
  578. end;
  579. procedure TRJSON.SetItems(AIndex: Integer; const [ref] AValue: TRJSON);
  580. begin
  581. SetItems('[' + AIndex.ToString + ']', AValue);
  582. end;
  583. function TRJSON.GetCount: Integer;
  584. var
  585. jvTemp: TJSONValue;
  586. begin
  587. jvTemp := GetJSONValue;
  588. if jvTemp is TJSONArray then
  589. Result := TJSONArray(jvTemp).Count
  590. else if jvTemp is TJSONObject then
  591. Result := TJSONObject(jvTemp).Count
  592. else
  593. Result := 0;
  594. end;
  595. function TRJSON.GetIndex: Integer;
  596. var
  597. strTmp: string;
  598. begin
  599. Result := -1;
  600. strTmp := FPath.Substring(FPath.LastIndexOf('[') + 1);
  601. if strTmp.EndsWith(']') then
  602. Result := StrToIntDef(strTmp.TrimRight([']']), -1);
  603. end;
  604. function TRJSON.GetKey: string;
  605. begin
  606. Result := FPath.Substring(FPath.LastIndexOf('.') + 1);
  607. if Result.EndsWith(']') then
  608. Result := '';
  609. end;
  610. function TRJSON.RootIs<T>: boolean;
  611. begin
  612. Result := FRoot.Data is T;
  613. end;
  614. function TRJSON.ValueIs<T>: boolean;
  615. begin
  616. Result := GetJSONValue is T;
  617. end;
  618. procedure TRJSON.Reset;
  619. begin
  620. FRoot := TRJSONRoot.Create;
  621. FPath := '';
  622. end;
  623. function TRJSON.Format(Indentation: Integer): string;
  624. var
  625. LValue: TJSONValue;
  626. begin
  627. Result := '';
  628. LValue := GetJSONValue;
  629. if LValue <> nil then
  630. begin
  631. if Indentation > 0 then
  632. Result := LValue.Format(Indentation)
  633. else
  634. Result := LValue.ToString;
  635. end;
  636. end;
  637. procedure TRJSON.ParseJSONValue(const AData: string; AUseBool: boolean; ARaiseExc: boolean);
  638. begin
  639. Reset;
  640. FRoot.Data := TJSONValue.ParseJSONValue(AData, AUseBool, ARaiseExc);
  641. end;
  642. procedure TRJSON.LoadFromFile(const AFileName: string; AUseBool: boolean; ARaiseExc: boolean);
  643. begin
  644. ParseJSONValue(TFile.ReadAllText(AFileName, TEncoding.UTF8), AUseBool, ARaiseExc);
  645. end;
  646. procedure TRJSON.SaveToFile(const AFileName: string; AIndentation: Integer; AWriteBOM: boolean; ATrailingLineBreak: boolean);
  647. var
  648. strs: TStrings;
  649. begin
  650. strs := TStringList.Create;
  651. try
  652. strs.WriteBOM := AWriteBOM;
  653. strs.TrailingLineBreak := ATrailingLineBreak;
  654. strs.Text := Format(AIndentation);
  655. strs.SaveToFile(AFileName, TEncoding.UTF8);
  656. finally
  657. strs.Free;
  658. end;
  659. end;
  660. { TRJSON }
  661. { ============================================================================ }
  662. end.