2
0

Quick.JSON.Helper.pas 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. { ***************************************************************************
  2. Copyright (c) 2015-2020 Kike Pérez
  3. Unit : Quick.JSON.Helper
  4. Description : Utils for working with JSON
  5. Author : Kike Pérez
  6. Version : 1.1
  7. Created : 27/01/2017
  8. Modified : 16/01/2020
  9. This file is part of QuickLib: https://github.com/exilon/QuickLib
  10. ***************************************************************************
  11. Licensed under the Apache License, Version 2.0 (the "License");
  12. you may not use this file except in compliance with the License.
  13. You may obtain a copy of the License at
  14. http://www.apache.org/licenses/LICENSE-2.0
  15. Unless required by applicable law or agreed to in writing, software
  16. distributed under the License is distributed on an "AS IS" BASIS,
  17. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. See the License for the specific language governing permissions and
  19. limitations under the License.
  20. *************************************************************************** }
  21. unit Quick.JSON.Helper;
  22. {$i QuickLib.inc}
  23. interface
  24. uses
  25. Classes,
  26. SysUtils,
  27. Quick.Json.Serializer;
  28. type
  29. TObjectHelper = class helper for TObject
  30. public
  31. function ToJson : string;
  32. procedure FromJson(const json : string);
  33. procedure Clone(cObj : TObject);
  34. end;
  35. //only public properties will be cloned or gotten
  36. var
  37. GlobalJsonIdenter : Boolean = True;
  38. implementation
  39. function TObjectHelper.ToJSON : string;
  40. var
  41. Serializer : TJsonSerializer;
  42. begin
  43. Result := '';
  44. try
  45. Serializer := TJsonSerializer.Create(TSerializeLevel.{$IFDEF FPC}slPublishedProperty{$ELSE}slPublicProperty{$ENDIF},True);
  46. try
  47. Result := Serializer.ObjectToJson(Self,GlobalJsonIdenter);
  48. finally
  49. Serializer.Free;
  50. end;
  51. except
  52. on e : Exception do raise Exception.Create(e.Message);
  53. end;
  54. end;
  55. procedure TObjectHelper.FromJson(const json :string);
  56. var
  57. Serializer : TJsonSerializer;
  58. begin
  59. try
  60. Serializer := TJsonSerializer.Create(TSerializeLevel.{$IFDEF FPC}slPublishedProperty{$ELSE}slPublicProperty{$ENDIF},True);
  61. try
  62. Serializer.JsonToObject(Self,json);
  63. finally
  64. Serializer.Free;
  65. end;
  66. except
  67. on e : Exception do raise Exception.Create(e.Message);
  68. end;
  69. end;
  70. procedure TObjectHelper.Clone(cObj : TObject);
  71. begin
  72. cObj.FromJson(Self.ToJson);
  73. end;
  74. end.