UJSONFunctions.pas 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. unit UJSONFunctions;
  2. {$IFDEF FPC}
  3. {$MODE Delphi}
  4. {$ENDIF}
  5. { Copyright (c) 2016 by Albert Molina
  6. Distributed under the MIT software license, see the accompanying file LICENSE
  7. or visit http://www.opensource.org/licenses/mit-license.php.
  8. This unit is a part of Pascal Coin, a P2P crypto currency without need of
  9. historical operations.
  10. If you like it, consider a donation using BitCoin:
  11. 16K3HCZRhFUtM8GdWRcfKeaa6KsuyxZaYk
  12. }
  13. interface
  14. Uses
  15. {$IFDEF FPC}
  16. fpjson, jsonparser,
  17. {$ELSE}
  18. DBXJSON,
  19. {$ENDIF}
  20. SysUtils, DateUtils, Variants, Classes, ULog;
  21. Type
  22. {$IFDEF FPC}
  23. TJSONValue = TJSONData;
  24. {$ENDIF}
  25. TPCJSONData = Class
  26. private
  27. FParent : TPCJSONData;
  28. protected
  29. Function ToJSONFormatted(pretty:Boolean;Const prefix : AnsiString) : AnsiString; virtual; abstract;
  30. public
  31. Constructor Create; virtual;
  32. Destructor Destroy; override;
  33. Class Function ParseJSONValue(Const JSONObject : String) : TPCJSONData; overload;
  34. Class Function ParseJSONValue(Const JSONObject : TBytes) : TPCJSONData; overload;
  35. Class Function _GetCount : Integer;
  36. Function ToJSON(pretty : Boolean) : AnsiString;
  37. Procedure SaveToStream(Stream : TStream);
  38. Procedure Assign(PCJSONData : TPCJSONData);
  39. End;
  40. TPCJSONDataClass = Class of TPCJSONData;
  41. { TPCJSONVariantValue }
  42. TPCJSONVariantValue = Class(TPCJSONData)
  43. private
  44. FOldValue : Variant;
  45. FWritable : Boolean;
  46. FValue: Variant;
  47. procedure SetValue(const Value: Variant);
  48. protected
  49. Function ToJSONFormatted(pretty:Boolean;const prefix : AnsiString) : AnsiString; override;
  50. public
  51. Constructor Create; override;
  52. Constructor CreateFromJSONValue(JSONValue : TJSONValue);
  53. Property Value : Variant read FValue write SetValue;
  54. Function AsString(DefValue : String) : String;
  55. Function AsInteger(DefValue : Integer) : Integer;
  56. Function AsInt64(DefValue : Int64) : Int64;
  57. Function AsDouble(DefValue : Double) : Double;
  58. Function AsBoolean(DefValue : Boolean) : Boolean;
  59. Function AsDateTime(DefValue : TDateTime) : TDateTime;
  60. Function AsCurrency(DefValue : Currency) : Currency;
  61. Function AsCardinal(DefValue : Cardinal) : Cardinal;
  62. End;
  63. TPCJSONNameValue = Class(TPCJSONData)
  64. private
  65. FName: String;
  66. FValue: TPCJSONData;
  67. FFreeValue : Boolean;
  68. procedure SetValue(const Value: TPCJSONData);
  69. protected
  70. Function ToJSONFormatted(pretty:Boolean;const prefix : AnsiString) : AnsiString; override;
  71. public
  72. Constructor Create(AName : String);
  73. Destructor Destroy; override;
  74. Property Name : String read FName;
  75. Property Value : TPCJSONData read FValue write SetValue;
  76. End;
  77. TPCJSONArray = class;
  78. TPCJSONObject = Class;
  79. TPCJSONList = Class(TPCJSONData)
  80. private
  81. FList : TList;
  82. function GetItems(Index: Integer): TPCJSONData;
  83. procedure SetItems(Index: Integer; const Value: TPCJSONData);
  84. protected
  85. Function GetIndexAsVariant(Index : Integer) : TPCJSONVariantValue;
  86. Function GetIndexAsArray(Index : Integer) : TPCJSONArray;
  87. Function GetIndexAsObject(Index : Integer) : TPCJSONObject;
  88. Procedure CheckCanInsert(Index:Integer; PCJSONData:TPCJSONData); virtual;
  89. public
  90. Constructor Create; override;
  91. Destructor Destroy; override;
  92. Property Items[Index:Integer] : TPCJSONData read GetItems write SetItems;
  93. Procedure Insert(Index:Integer; PCJSONData:TPCJSONData);
  94. Procedure Delete(index : Integer);
  95. function Count : Integer;
  96. Procedure Clear;
  97. End;
  98. TPCJSONArray = class(TPCJSONList)
  99. private
  100. Procedure GrowToIndex(index : Integer);
  101. function GetItemOfType(Index: Integer; DataClass:TPCJSONDataClass): TPCJSONData;
  102. protected
  103. Function ToJSONFormatted(pretty:Boolean;const prefix : AnsiString) : AnsiString; override;
  104. public
  105. Constructor Create; override;
  106. Constructor CreateFromJSONArray(JSONArray : TJSONArray);
  107. Destructor Destroy; override;
  108. Function GetAsVariant(index : Integer) : TPCJSONVariantValue;
  109. Function GetAsObject(index : Integer) : TPCJSONObject;
  110. Function GetAsArray(index : Integer) : TPCJSONArray;
  111. end;
  112. TPCJSONObject = Class(TPCJSONList)
  113. private
  114. Function GetIndexOrCreateName(Name : String) : Integer;
  115. Function GetByName(Name : String) : TPCJSONNameValue;
  116. protected
  117. Function ToJSONFormatted(pretty:Boolean;const prefix : AnsiString) : AnsiString; override;
  118. Procedure CheckCanInsert(Index:Integer; PCJSONData:TPCJSONData); override;
  119. Procedure CheckValidName(Name : String);
  120. public
  121. Constructor Create; override;
  122. Constructor CreateFromJSONObject(JSONObject : TJSONObject);
  123. Destructor Destroy; override;
  124. Function FindName(Name : String) : TPCJSONNameValue;
  125. Function IndexOfName(Name : String) : Integer;
  126. Procedure DeleteName(Name : String);
  127. Function GetAsVariant(Name : String) : TPCJSONVariantValue;
  128. Function GetAsObject(Name : String) : TPCJSONObject;
  129. Function GetAsArray(Name : String) : TPCJSONArray;
  130. Function AsString(ParamName : String; DefValue : String) : String;
  131. Function AsInteger(ParamName : String; DefValue : Integer) : Integer;
  132. Function AsCardinal(ParamName : String; DefValue : Cardinal) : Cardinal;
  133. Function AsInt64(ParamName : String; DefValue : Int64) : Int64;
  134. Function AsDouble(ParamName : String; DefValue : Double) : Double;
  135. Function AsBoolean(ParamName : String; DefValue : Boolean) : Boolean;
  136. Function AsDateTime(ParamName : String; DefValue : TDateTime) : TDateTime;
  137. Function AsCurrency(ParamName : String; DefValue : Currency) : Currency;
  138. Function SaveAsStream(ParamName : String; Stream : TStream) : Integer;
  139. Function LoadAsStream(ParamName : String; Stream : TStream) : Integer;
  140. Function GetNameValue(index : Integer) : TPCJSONNameValue;
  141. Procedure SetAs(Name : String; Value : TPCJSONData);
  142. End;
  143. EPCParametresError = Class(Exception);
  144. implementation
  145. Function UTF8JSONEncode(plainTxt : String; includeSeparator : Boolean) : String;
  146. Var ws : WideString;
  147. i : Integer;
  148. Begin
  149. ws := UTF8Encode(plainTxt);
  150. {ALERT:
  151. UTF8Encode function deletes last char if equal to #0, so we put it manually
  152. }
  153. if copy(plainTxt,length(plainTxt),1)=#0 then ws := ws + #0;
  154. i := 1;
  155. result := '"';
  156. while i <= length(ws) do
  157. begin
  158. case ws[i] of
  159. '/', '\', '"': result := result + '\' + ws[i];
  160. #8: result := result + '\b';
  161. #9: result := result + '\t';
  162. #10: result := result + '\n';
  163. #13: result := result + '\r';
  164. #12: result := result + '\f';
  165. else
  166. if (ord(ws[i]) < 32) Or (ord(ws[i])>122) then
  167. result := result + '\u' + inttohex(ord(ws[i]), 4)
  168. else
  169. result := result + ws[i];
  170. end;
  171. inc(i);
  172. end;
  173. result := result + '"';
  174. End;
  175. { TPCJSONArray }
  176. constructor TPCJSONArray.Create;
  177. begin
  178. inherited;
  179. end;
  180. constructor TPCJSONArray.CreateFromJSONArray(JSONArray: TJSONArray);
  181. Var i : Integer;
  182. begin
  183. Create;
  184. {$IFDEF FPC}
  185. for i := 0 to JSONArray.Count - 1 do begin
  186. if (JSONArray.Items[i] is TJSONArray) then begin
  187. Insert(i,TPCJSONArray.CreateFromJSONArray(TJSONArray(JSONArray.Items[i])));
  188. end else if (JSONArray.Items[i] is TJSONObject) then begin
  189. Insert(i,TPCJSONObject.CreateFromJSONObject(TJSONObject(JSONArray.Items[i])));
  190. end else if (JSONArray.Items[i] is TJSONValue) then begin
  191. Insert(i,TPCJSONVariantValue.CreateFromJSONValue(TJSONValue(JSONArray.Items[i])));
  192. end else raise EPCParametresError.Create('Invalid TJSON Data: '+JSONArray.Items[i].ClassName);
  193. end;
  194. {$ELSE}
  195. for i := 0 to JSONArray.Size - 1 do begin
  196. if (JSONArray.Get(i) is TJSONArray) then begin
  197. Insert(i,TPCJSONArray.CreateFromJSONArray(TJSONArray(JSONArray.Get(i))));
  198. end else if (JSONArray.Get(i) is TJSONObject) then begin
  199. Insert(i,TPCJSONObject.CreateFromJSONObject(TJSONObject(JSONArray.Get(i))));
  200. end else if (JSONArray.Get(i) is TJSONValue) then begin
  201. Insert(i,TPCJSONVariantValue.CreateFromJSONValue(TJSONValue(JSONArray.Get(i))));
  202. end else raise EPCParametresError.Create('Invalid TJSON Data: '+JSONArray.Get(i).ClassName);
  203. end;
  204. {$ENDIF}
  205. end;
  206. destructor TPCJSONArray.Destroy;
  207. begin
  208. inherited;
  209. end;
  210. function TPCJSONArray.GetAsArray(index: Integer): TPCJSONArray;
  211. begin
  212. Result := GetItemOfType(index,TPCJSONArray) as TPCJSONArray;
  213. end;
  214. function TPCJSONArray.GetAsObject(index: Integer): TPCJSONObject;
  215. begin
  216. Result := GetItemOfType(index,TPCJSONObject) as TPCJSONObject;
  217. end;
  218. function TPCJSONArray.GetAsVariant(index: Integer): TPCJSONVariantValue;
  219. begin
  220. Result := GetItemOfType(index,TPCJSONVariantValue) as TPCJSONVariantValue;
  221. end;
  222. function TPCJSONArray.GetItemOfType(Index: Integer;
  223. DataClass: TPCJSONDataClass): TPCJSONData;
  224. Var V,New : TPCJSONData;
  225. begin
  226. GrowToIndex(Index);
  227. V := GetItems(index);
  228. if Not (V is DataClass) then begin
  229. New := DataClass.Create;
  230. Items[index] := New;
  231. V := New;
  232. end;
  233. Result := V as DataClass;
  234. end;
  235. procedure TPCJSONArray.GrowToIndex(index: Integer);
  236. begin
  237. While (index>=Count) do Insert(Count,TPCJSONVariantValue.Create);
  238. end;
  239. function TPCJSONArray.ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString;
  240. Var i : Integer;
  241. begin
  242. If pretty then Result := prefix+'['
  243. else Result := '[';
  244. for i := 0 to Count - 1 do begin
  245. if (i>0) then begin
  246. Result := Result+',';
  247. If pretty then Result :=Result +#10+prefix;
  248. end;
  249. Result := Result + Items[i].ToJSONFormatted(pretty,prefix+' ');
  250. end;
  251. Result := Result+']';
  252. end;
  253. { TPCJSONList }
  254. procedure TPCJSONList.CheckCanInsert(Index: Integer; PCJSONData: TPCJSONData);
  255. begin
  256. if (Index<0) Or (Index>Count) then raise Exception.Create('Invalid insert at index '+Inttostr(Index)+' (Count:'+Inttostr(Count)+')');
  257. end;
  258. procedure TPCJSONList.Clear;
  259. begin
  260. while (FList.Count>0) do Delete(FList.Count-1);
  261. end;
  262. function TPCJSONList.Count: Integer;
  263. begin
  264. Result := FList.Count;
  265. end;
  266. constructor TPCJSONList.Create;
  267. begin
  268. inherited;
  269. FParent := Nil;
  270. FList := TList.Create;
  271. end;
  272. procedure TPCJSONList.Delete(index: Integer);
  273. Var M : TPCJSONData;
  274. begin
  275. M := GetItems(index);
  276. FList.Delete(index);
  277. M.Free;
  278. end;
  279. destructor TPCJSONList.Destroy;
  280. begin
  281. Clear;
  282. FList.Free;
  283. inherited;
  284. end;
  285. function TPCJSONList.GetIndexAsArray(Index: Integer): TPCJSONArray;
  286. Var D : TPCJSONData;
  287. begin
  288. D := GetItems(Index);
  289. if (Not (D is TPCJSONArray)) then begin
  290. Result := TPCJSONArray.Create;
  291. SetItems(Index,Result);
  292. D.Free;
  293. end else Result := TPCJSONArray(D);
  294. end;
  295. function TPCJSONList.GetIndexAsObject(Index: Integer): TPCJSONObject;
  296. Var D : TPCJSONData;
  297. begin
  298. D := GetItems(Index);
  299. if (Not (D is TPCJSONObject)) then begin
  300. Result := TPCJSONObject.Create;
  301. SetItems(Index,Result);
  302. D.Free;
  303. end else Result := TPCJSONObject(D);
  304. end;
  305. function TPCJSONList.GetIndexAsVariant(Index: Integer): TPCJSONVariantValue;
  306. Var D : TPCJSONData;
  307. begin
  308. D := GetItems(Index);
  309. if (Not (D is TPCJSONVariantValue)) then begin
  310. Result := TPCJSONVariantValue.Create;
  311. SetItems(Index,Result);
  312. D.Free;
  313. end else Result := TPCJSONVariantValue(D);
  314. end;
  315. function TPCJSONList.GetItems(Index: Integer): TPCJSONData;
  316. begin
  317. Result := FList.Items[Index];
  318. end;
  319. procedure TPCJSONList.Insert(Index: Integer; PCJSONData: TPCJSONData);
  320. begin
  321. CheckCanInsert(Index,PCJSONData);
  322. FList.Insert(Index,PCJSONData);
  323. end;
  324. procedure TPCJSONList.SetItems(Index: Integer; const Value: TPCJSONData);
  325. Var OldP : TPCJSONData;
  326. begin
  327. OldP := FList.Items[Index];
  328. Try
  329. FList.Items[Index] := Value;
  330. Finally
  331. OldP.Free;
  332. End;
  333. end;
  334. { TPCJSONVariantValue }
  335. Function VariantToDouble(Value : Variant) : Double;
  336. Var s : String;
  337. Begin
  338. Result := 0;
  339. Case varType(Value) of
  340. varSmallint, varInteger, varSingle, varDouble,
  341. varCurrency : Result := Value;
  342. Else
  343. Begin
  344. s := VarToStr(Value);
  345. If s='' Then Abort
  346. Else Result := StrToFloat(s);
  347. End;
  348. End;
  349. End;
  350. function TPCJSONVariantValue.AsBoolean(DefValue: Boolean): Boolean;
  351. begin
  352. try
  353. Result := VarAsType(Value,varBoolean);
  354. except
  355. Result := DefValue;
  356. end;
  357. end;
  358. function TPCJSONVariantValue.AsCurrency(DefValue: Currency): Currency;
  359. begin
  360. try
  361. Result := VariantToDouble(Value);
  362. except
  363. Result := DefValue;
  364. end;
  365. end;
  366. function TPCJSONVariantValue.AsCardinal(DefValue: Cardinal): Cardinal;
  367. begin
  368. Result := Cardinal( StrToIntDef(VarToStrDef(Value,''),DefValue) );
  369. end;
  370. function TPCJSONVariantValue.AsDateTime(DefValue: TDateTime): TDateTime;
  371. begin
  372. try
  373. Result := VarAsType(Value,varDate);
  374. except
  375. Result := DefValue;
  376. end;
  377. end;
  378. function TPCJSONVariantValue.AsDouble(DefValue: Double): Double;
  379. begin
  380. try
  381. Result := VariantToDouble(Value);
  382. except
  383. Result := DefValue;
  384. end;
  385. end;
  386. function TPCJSONVariantValue.AsInt64(DefValue: Int64): Int64;
  387. begin
  388. Result := StrToInt64Def(VarToStrDef(Value,''),DefValue);
  389. end;
  390. function TPCJSONVariantValue.AsInteger(DefValue: Integer): Integer;
  391. begin
  392. Result := StrToIntDef(VarToStrDef(Value,''),DefValue);
  393. end;
  394. function TPCJSONVariantValue.AsString(DefValue: String): String;
  395. begin
  396. try
  397. Case VarType(Value) of
  398. varNull : Result := '';
  399. varSmallint, varInteger :
  400. Begin
  401. Result := inttostr(Value);
  402. End;
  403. varSingle, varDouble,varCurrency :
  404. Begin
  405. Result := FloatToStr(VariantToDouble(Value));
  406. End;
  407. varDate : Result := DateTimeToStr(Value);
  408. Else Result := VarToStr(Value);
  409. End;
  410. except
  411. Result := DefValue;
  412. end;
  413. end;
  414. constructor TPCJSONVariantValue.Create;
  415. begin
  416. inherited;
  417. FValue := Null;
  418. FOldValue := Unassigned;
  419. FWritable := False;
  420. end;
  421. constructor TPCJSONVariantValue.CreateFromJSONValue(JSONValue: TJSONValue);
  422. {$IFnDEF FPC}
  423. Var d : Double;
  424. i64 : Integer;
  425. ds,ts : Char;
  426. {$ENDIF}
  427. begin
  428. Create;
  429. {$IFDEF FPC}
  430. Value := JSONValue.Value;
  431. {$ELSE}
  432. if JSONValue is TJSONNumber then begin
  433. d := TJSONNumber(JSONValue).AsDouble;
  434. if Pos('.',JSONValue.ToString)>0 then i64 := 0
  435. else i64 := TJSONNumber(JSONValue).AsInt;
  436. ds := DecimalSeparator;
  437. ts := ThousandSeparator;
  438. DecimalSeparator := '.';
  439. ThousandSeparator := ',';
  440. Try
  441. if FormatFloat('0.###########',d)=inttostr(i64) then
  442. Value := i64
  443. else Value := d;
  444. Finally
  445. DecimalSeparator := ds;
  446. ThousandSeparator := ts;
  447. End;
  448. end else if JSONValue is TJSONTrue then Value := true
  449. else if JSONValue is TJSONFalse then Value := false
  450. else if JSONValue is TJSONNull then Value := Null
  451. else Value := JSONValue.Value;
  452. {$ENDIF}
  453. end;
  454. procedure TPCJSONVariantValue.SetValue(const Value: Variant);
  455. begin
  456. FOldValue := FValue;
  457. FValue := Value;
  458. end;
  459. function TPCJSONVariantValue.ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString;
  460. Var ds,ts : Char;
  461. begin
  462. Case VarType(Value) of
  463. varSmallint,varInteger,varByte,varWord,
  464. varLongWord,varInt64 : Result := VarToStr(Value);
  465. varBoolean : if (Value) then Result := 'true' else Result:='false';
  466. varNull : Result := 'null';
  467. varDate,varDouble : begin
  468. ds := DecimalSeparator;
  469. ts := ThousandSeparator;
  470. DecimalSeparator := '.';
  471. ThousandSeparator := ',';
  472. try
  473. Result := FormatFloat('0.###########',Value);
  474. finally
  475. DecimalSeparator := ds;
  476. ThousandSeparator := ts;
  477. end;
  478. end
  479. else
  480. Result := UTF8JSONEncode(VarToStr(Value),true);
  481. end;
  482. end;
  483. { TPCJSONObject }
  484. function TPCJSONObject.AsBoolean(ParamName: String; DefValue: Boolean): Boolean;
  485. Var v : Variant;
  486. VV : TPCJSONVariantValue;
  487. begin
  488. VV := GetAsVariant(ParamName);
  489. if (VarType(VV.Value)=varNull) AND (VarType( VV.FOldValue ) = varEmpty) then begin
  490. Result := DefValue;
  491. Exit;
  492. end;
  493. v := GetAsVariant(ParamName).Value;
  494. try
  495. if VarIsNull(v) then Result := DefValue
  496. else Result := VarAsType(v,varBoolean);
  497. except
  498. Result := DefValue;
  499. end;
  500. end;
  501. function TPCJSONObject.AsCardinal(ParamName: String; DefValue: Cardinal): Cardinal;
  502. begin
  503. Result := Cardinal(AsInt64(ParamName,DefValue));
  504. end;
  505. function TPCJSONObject.AsCurrency(ParamName: String; DefValue: Currency): Currency;
  506. Var v : Variant;
  507. VV : TPCJSONVariantValue;
  508. begin
  509. VV := GetAsVariant(ParamName);
  510. if (VarType(VV.Value)=varNull) AND (VarType( VV.FOldValue ) = varEmpty) then begin
  511. Result := DefValue;
  512. Exit;
  513. end;
  514. v := GetAsVariant(ParamName).Value;
  515. try
  516. if VarIsNull(v) then Result := DefValue
  517. else Result := VariantToDouble(v);
  518. except
  519. Result := DefValue;
  520. end;
  521. end;
  522. function TPCJSONObject.AsDateTime(ParamName: String;
  523. DefValue: TDateTime): TDateTime;
  524. Var v : Variant;
  525. VV : TPCJSONVariantValue;
  526. begin
  527. VV := GetAsVariant(ParamName);
  528. if (VarType(VV.Value)=varNull) AND (VarType( VV.FOldValue ) = varEmpty) then begin
  529. Result := DefValue;
  530. Exit;
  531. end;
  532. v := GetAsVariant(ParamName).Value;
  533. try
  534. if VarIsNull(v) then Result := DefValue
  535. else Result := VarAsType(v,varDate);
  536. except
  537. Result := DefValue;
  538. end;
  539. end;
  540. function TPCJSONObject.AsDouble(ParamName: String; DefValue: Double): Double;
  541. Var v : Variant;
  542. VV : TPCJSONVariantValue;
  543. begin
  544. VV := GetAsVariant(ParamName);
  545. if (VarType(VV.Value)=varNull) AND (VarType( VV.FOldValue ) = varEmpty) then begin
  546. Result := DefValue;
  547. Exit;
  548. end;
  549. v := GetAsVariant(ParamName).Value;
  550. try
  551. if VarIsNull(v) then Result := DefValue
  552. else Result := VariantToDouble(v);
  553. except
  554. Result := DefValue;
  555. end;
  556. end;
  557. function TPCJSONObject.AsInt64(ParamName: String; DefValue: Int64): Int64;
  558. Var v : Variant;
  559. VV : TPCJSONVariantValue;
  560. begin
  561. VV := GetAsVariant(ParamName);
  562. if (VarType(VV.Value)=varNull) AND (VarType( VV.FOldValue ) = varEmpty) then begin
  563. Result := DefValue;
  564. Exit;
  565. end;
  566. v := GetAsVariant(ParamName).Value;
  567. try
  568. if VarIsNull(v) then Result := DefValue
  569. else Result := StrToInt64Def(VarToStrDef(v,''),DefValue);
  570. except
  571. Result := DefValue;
  572. end;
  573. end;
  574. function TPCJSONObject.AsInteger(ParamName: String; DefValue: Integer): Integer;
  575. Var v : Variant;
  576. VV : TPCJSONVariantValue;
  577. begin
  578. VV := GetAsVariant(ParamName);
  579. if (VarType(VV.Value)=varNull) AND (VarType( VV.FOldValue ) = varEmpty) then begin
  580. Result := DefValue;
  581. Exit;
  582. end;
  583. v := GetAsVariant(ParamName).Value;
  584. try
  585. if VarIsNull(v) then Result := DefValue
  586. else Result := StrToIntDef(VarToStrDef(v,''),DefValue);
  587. except
  588. Result := DefValue;
  589. end;
  590. end;
  591. function TPCJSONObject.AsString(ParamName, DefValue: String): String;
  592. Var v : Variant;
  593. VV : TPCJSONVariantValue;
  594. begin
  595. VV := GetAsVariant(ParamName);
  596. if (VarType(VV.Value)=varNull) AND (VarType( VV.FOldValue ) = varEmpty) then begin
  597. Result := DefValue;
  598. Exit;
  599. end;
  600. v := GetAsVariant(ParamName).Value;
  601. try
  602. Case VarType(V) of
  603. varNull : Result := '';
  604. varSmallint, varInteger :
  605. Begin
  606. Result := inttostr(v);
  607. End;
  608. varSingle, varDouble,varCurrency :
  609. Begin
  610. Result := FloatToStr(VariantToDouble(v));
  611. End;
  612. varDate : Result := DateTimeToStr(v);
  613. Else Result := VarToStr(v);
  614. End;
  615. except
  616. Result := DefValue;
  617. end;
  618. end;
  619. procedure TPCJSONObject.CheckCanInsert(Index: Integer; PCJSONData: TPCJSONData);
  620. begin
  621. inherited;
  622. if Not Assigned(PCJSONData) then raise Exception.Create('Object is nil');
  623. if Not (PCJSONData is TPCJSONNameValue) then raise Exception.Create('Object inside a '+TPCJSONData.ClassName+' must be a '+TPCJSONNameValue.ClassName+' (currently '+PCJSONData.ClassName+')');
  624. end;
  625. procedure TPCJSONObject.CheckValidName(Name: String);
  626. Var i : Integer;
  627. begin
  628. for i := 1 to Length(Name) do begin
  629. if i=1 then begin
  630. if Not (Name[i] in ['a'..'z','A'..'Z','0'..'9','_','.']) then raise Exception.Create(Format('Invalid char %s at pos %d/%d',[Name[i],i,length(Name)]));
  631. end else begin
  632. if Not (Name[i] in ['a'..'z','A'..'Z','0'..'9','_','-','.']) then raise Exception.Create(Format('Invalid char %s at pos %d/%d',[Name[i],i,length(Name)]));
  633. end;
  634. end;
  635. end;
  636. constructor TPCJSONObject.Create;
  637. begin
  638. inherited;
  639. end;
  640. constructor TPCJSONObject.CreateFromJSONObject(JSONObject: TJSONObject);
  641. var i,i2 : Integer;
  642. {$IFDEF FPC}
  643. aname : TJSONStringType;
  644. {$ENDIF}
  645. begin
  646. Create;
  647. {$IFDEF FPC}
  648. for i := 0 to JSONObject.Count - 1 do begin
  649. aname := JSONObject.Names[i];
  650. i2 := GetIndexOrCreateName(JSONObject.Names[i]);
  651. if (JSONObject.Types[ aname ] = jtArray) then begin
  652. (Items[i2] as TPCJSONNameValue).Value := TPCJSONArray.CreateFromJSONArray(JSONObject.Arrays[aname]);
  653. end else if (JSONObject.Types[ aname ] = jtObject) then begin
  654. (Items[i2] as TPCJSONNameValue).Value := TPCJSONObject.CreateFromJSONObject(JSONObject.Objects[aname]);
  655. end else if (JSONObject.Types[ aname ] in [jtBoolean,jtNull,jtNumber,jtString]) then begin
  656. (Items[i2] as TPCJSONNameValue).Value := TPCJSONVariantValue.CreateFromJSONValue(JSONObject.Items[i]);
  657. end else raise EPCParametresError.Create('Invalid TJSON Data in JSONObject.'+aname+': '+JSONObject.Items[i].ClassName);
  658. end;
  659. {$ELSE}
  660. for i := 0 to JSONObject.Size - 1 do begin
  661. i2 := GetIndexOrCreateName(JSONObject.Get(i).JsonString.Value);
  662. if (JSONObject.Get(i).JsonValue is TJSONArray) then begin
  663. (Items[i2] as TPCJSONNameValue).Value := TPCJSONArray.CreateFromJSONArray(TJSONArray(JSONObject.Get(i).JsonValue));
  664. end else if (JSONObject.Get(i).JsonValue is TJSONObject) then begin
  665. (Items[i2] as TPCJSONNameValue).Value := TPCJSONObject.CreateFromJSONObject(TJSONObject(JSONObject.Get(i).JsonValue));
  666. end else if (JSONObject.Get(i).JsonValue is TJSONValue) then begin
  667. (Items[i2] as TPCJSONNameValue).Value := TPCJSONVariantValue.CreateFromJSONValue(TJSONValue(JSONObject.Get(i).JsonValue));
  668. end else raise EPCParametresError.Create('Invalid TJSON Data in JSONObject.'+JSONObject.Get(i).JsonString.Value+': '+JSONObject.Get(i).ClassName);
  669. end;
  670. {$ENDIF}
  671. end;
  672. procedure TPCJSONObject.DeleteName(Name: String);
  673. Var i : Integer;
  674. begin
  675. i := IndexOfName(Name);
  676. if (i>=0) then begin
  677. Delete(i);
  678. end;
  679. end;
  680. destructor TPCJSONObject.Destroy;
  681. begin
  682. inherited;
  683. end;
  684. function TPCJSONObject.FindName(Name: String): TPCJSONNameValue;
  685. Var i : Integer;
  686. begin
  687. i := IndexOfName(Name);
  688. Result := Nil;
  689. if (i>=0) then Result := Items[i] as TPCJSONNameValue;
  690. end;
  691. function TPCJSONObject.GetAsArray(Name: String): TPCJSONArray;
  692. Var NV : TPCJSONNameValue;
  693. V : TPCJSONData;
  694. begin
  695. NV := GetByName(Name);
  696. if Not (NV.Value is TPCJSONArray) then begin
  697. NV.Value := TPCJSONArray.Create;
  698. end;
  699. Result := NV.Value as TPCJSONArray;
  700. end;
  701. function TPCJSONObject.GetAsObject(Name: String): TPCJSONObject;
  702. Var NV : TPCJSONNameValue;
  703. V : TPCJSONData;
  704. begin
  705. NV := GetByName(Name);
  706. if Not (NV.Value is TPCJSONObject) then begin
  707. NV.Value := TPCJSONObject.Create;
  708. end;
  709. Result := NV.Value as TPCJSONObject;
  710. end;
  711. function TPCJSONObject.GetAsVariant(Name: String): TPCJSONVariantValue;
  712. Var NV : TPCJSONNameValue;
  713. V : TPCJSONData;
  714. begin
  715. NV := GetByName(Name);
  716. if Not (NV.Value is TPCJSONVariantValue) then begin
  717. NV.Value := TPCJSONVariantValue.Create;
  718. end;
  719. Result := NV.Value as TPCJSONVariantValue;
  720. end;
  721. function TPCJSONObject.GetByName(Name: String): TPCJSONNameValue;
  722. Var i : Integer;
  723. begin
  724. i := GetIndexOrCreateName(Name);
  725. Result := Items[i] as TPCJSONNameValue;
  726. end;
  727. function TPCJSONObject.GetIndexOrCreateName(Name: String): Integer;
  728. Var
  729. NV : TPCJSONNameValue;
  730. Begin
  731. Result := IndexOfName(Name);
  732. if (Result<0) then begin
  733. CheckValidName(Name);
  734. NV := TPCJSONNameValue.Create(Name);
  735. Result := FList.Add(NV);
  736. end;
  737. end;
  738. function TPCJSONObject.GetNameValue(index: Integer): TPCJSONNameValue;
  739. begin
  740. Result := Items[index] as TPCJSONNameValue;
  741. end;
  742. function TPCJSONObject.IndexOfName(Name: String): Integer;
  743. begin
  744. for Result := 0 to FList.Count - 1 do begin
  745. if (Assigned(FList.Items[Result])) And (TObject(FList.Items[Result]) is TPCJSONNameValue) then begin
  746. If TPCJSONNameValue( FList.Items[Result] ).Name = Name then begin
  747. exit;
  748. end;
  749. end;
  750. end;
  751. Result := -1;
  752. end;
  753. function TPCJSONObject.LoadAsStream(ParamName: String; Stream: TStream): Integer;
  754. Var s : AnsiString;
  755. begin
  756. s := AsString(ParamName,'');
  757. if (s<>'') then begin
  758. Stream.Write(s[1],length(s));
  759. end;
  760. Result := Length(s);
  761. end;
  762. function TPCJSONObject.SaveAsStream(ParamName: String; Stream: TStream): Integer;
  763. Var s : AnsiString;
  764. begin
  765. Stream.Position := 0;
  766. SetLength(s,Stream.Size);
  767. Stream.Read(s[1],Stream.Size);
  768. GetAsVariant(ParamName).Value := s;
  769. end;
  770. procedure TPCJSONObject.SetAs(Name: String; Value: TPCJSONData);
  771. // When assigning a object with SetAs this will not be freed automatically
  772. Var NV : TPCJSONNameValue;
  773. V : TPCJSONData;
  774. i : Integer;
  775. begin
  776. i := GetIndexOrCreateName(Name);
  777. NV := Items[i] as TPCJSONNameValue;
  778. NV.Value := Value;
  779. NV.FFreeValue := false;
  780. end;
  781. function TPCJSONObject.ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString;
  782. Var i : Integer;
  783. begin
  784. if pretty then Result := prefix+'{'
  785. else Result := '{';
  786. for i := 0 to Count - 1 do begin
  787. if (i>0) then Begin
  788. Result := Result+',';
  789. If pretty then Result :=Result +#10+prefix;
  790. End;
  791. Result := Result + Items[i].ToJSONFormatted(pretty,prefix+' ');
  792. end;
  793. Result := Result+'}';
  794. end;
  795. { TPCJSONNameValue }
  796. constructor TPCJSONNameValue.Create(AName: String);
  797. begin
  798. inherited Create;
  799. FName := AName;
  800. FValue := TPCJSONData.Create;
  801. FFreeValue := True;
  802. end;
  803. destructor TPCJSONNameValue.Destroy;
  804. begin
  805. if FFreeValue then FValue.Free;
  806. inherited;
  807. end;
  808. procedure TPCJSONNameValue.SetValue(const Value: TPCJSONData);
  809. Var old : TPCJSONData;
  810. begin
  811. if FValue=Value then exit;
  812. old := FValue;
  813. FValue := Value;
  814. if FFreeValue then old.Free;
  815. FFreeValue := true;
  816. end;
  817. function TPCJSONNameValue.ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString;
  818. begin
  819. if pretty then Result := prefix else Result := '';
  820. Result := Result + UTF8JSONEncode(name,true)+':'+Value.ToJSONFormatted(pretty,prefix+' ');
  821. end;
  822. { TPCJSONData }
  823. Var _objectsCount : Integer;
  824. procedure TPCJSONData.Assign(PCJSONData: TPCJSONData);
  825. Var i : Integer;
  826. NV : TPCJSONNameValue;
  827. JSOND : TPCJSONData;
  828. s : AnsiString;
  829. begin
  830. if Not Assigned(PCJSONData) then Abort;
  831. if (PCJSONData is TPCJSONObject) AND (Self is TPCJSONObject) then begin
  832. for i := 0 to TPCJSONObject(PCJSONData).Count - 1 do begin
  833. NV := TPCJSONObject(PCJSONData).Items[i] as TPCJSONNameValue;
  834. if NV.Value is TPCJSONObject then begin
  835. TPCJSONObject(Self).GetAsObject(NV.Name).Assign(NV.Value);
  836. end else if NV.Value is TPCJSONArray then begin
  837. TPCJSONObject(Self).GetAsArray(NV.Name).Assign(NV.Value);
  838. end else if NV.Value is TPCJSONVariantValue then begin
  839. TPCJSONObject(Self).GetAsVariant(NV.Name).Assign(NV.Value);
  840. end else raise Exception.Create('Error in TPCJSONData.Assign decoding '+NV.Name+' ('+NV.Value.ClassName+')');
  841. end;
  842. end else if (PCJSONData is TPCJSONArray) AND (Self is TPCJSONArray) then begin
  843. for i := 0 to TPCJSONArray(PCJSONData).Count - 1 do begin
  844. JSOND := TPCJSONArray(PCJSONData).Items[i];
  845. s := JSOND.ToJSON(false);
  846. TPCJSONArray(Self).Insert(TPCJSONArray(Self).Count,TPCJSONData.ParseJSONValue(s));
  847. end;
  848. end else if (PCJSONData is TPCJSONVariantValue) AND (Self is TPCJSONVariantValue) then begin
  849. TPCJSONVariantValue(Self).Value := TPCJSONVariantValue(PCJSONData).Value;
  850. end else begin
  851. raise Exception.Create('Error in TPCJSONData.Assign assigning a '+PCJSONData.ClassName+' to a '+ClassName);
  852. end;
  853. end;
  854. constructor TPCJSONData.Create;
  855. begin
  856. inc(_objectsCount);
  857. end;
  858. destructor TPCJSONData.Destroy;
  859. begin
  860. dec(_objectsCount);
  861. inherited;
  862. end;
  863. class function TPCJSONData.ParseJSONValue(Const JSONObject: TBytes): TPCJSONData;
  864. Var JS : TJSONValue;
  865. {$IFDEF FPC}
  866. jss : TJSONStringType;
  867. i : Integer;
  868. {$ENDIF}
  869. begin
  870. Result := Nil;
  871. JS := Nil;
  872. {$IFDEF FPC}
  873. SetLength(jss,length(JSONObject));
  874. for i:=0 to High(JSONObject) do jss[i+1] := AnsiChar( JSONObject[i] );
  875. Try
  876. JS := GetJSON(jss);
  877. Except
  878. On E:Exception do begin
  879. TLog.NewLog(ltDebug,ClassName,'Error processing JSON: '+E.Message);
  880. end;
  881. end;
  882. {$ELSE}
  883. Try
  884. JS := TJSONObject.ParseJSONValue(JSONObject,0);
  885. Except
  886. On E:Exception do begin
  887. TLog.NewLog(ltDebug,ClassName,'Error processing JSON: '+E.Message);
  888. end;
  889. End;
  890. {$ENDIF}
  891. if Not Assigned(JS) then exit;
  892. Try
  893. if JS is TJSONObject then begin
  894. Result := TPCJSONObject.CreateFromJSONObject(TJSONObject(JS));
  895. end else if JS is TJSONArray then begin
  896. Result := TPCJSONArray.CreateFromJSONArray(TJSONArray(JS));
  897. end else if JS is TJSONValue then begin
  898. Result := TPCJSONVariantValue.CreateFromJSONValue(TJSONValue(JS));
  899. end else raise EPCParametresError.Create('Invalid TJSON Data type '+JS.ClassName);
  900. Finally
  901. JS.Free;
  902. End;
  903. end;
  904. procedure TPCJSONData.SaveToStream(Stream: TStream);
  905. Var s : AnsiString;
  906. begin
  907. s := ToJSON(false);
  908. Stream.Write(s[1],length(s));
  909. end;
  910. class function TPCJSONData.ParseJSONValue(Const JSONObject: String): TPCJSONData;
  911. begin
  912. Result := ParseJSONValue( TEncoding.ASCII.GetBytes(JSONObject) );
  913. end;
  914. function TPCJSONData.ToJSON(pretty: Boolean): AnsiString;
  915. begin
  916. Result := ToJSONFormatted(pretty,'');
  917. end;
  918. class function TPCJSONData._GetCount: Integer;
  919. begin
  920. Result := _objectsCount;
  921. end;
  922. initialization
  923. _objectsCount := 0;
  924. end.