Advertisement
danieleteti

DMVCFramework :: Null Object on property (manual version)

Feb 10th, 2021
1,106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.67 KB | None | 0 0
  1. program TestDMVCSerUnSerWithNulls;
  2.  
  3. {$APPTYPE CONSOLE}
  4.  
  5. {$R *.res}
  6.  
  7. uses
  8.   MVCFramework,
  9.   MVCFramework.Serializer.Commons,
  10.   MVCFramework.Nullables,
  11.   MVCFramework.Serializer.JsonDataObjects,
  12.   JsonDataObjects;
  13.  
  14. type
  15.   {$M+}
  16.   TObjB = class
  17.   private
  18.     FAnInt: integer;
  19.   public
  20.     property AnInt: integer read FAnInt write FAnInt;
  21.   end;
  22.  
  23.   TObjA = class
  24.   private
  25.     FObjB: TObjB;
  26.     FX: NullableString;
  27.     FY: NullableString;
  28.   public
  29.     property Y: NullableString read FY write FY;
  30.     property ObjB: TObjB read FObjB write FObjB;
  31.     property X: NullableString read FX write FX;
  32.   end;
  33.  
  34.   TObjC = class
  35.   private
  36.     FObjA: TObjA;
  37.     fPropStr: String;
  38.   public
  39.     property PropStr: String read fPropStr write fPropStr;
  40.     property ObjA: TObjA read FObjA write FObjA;
  41.   end;
  42.  
  43. procedure Test;
  44. var
  45.   s: string;
  46.   lSer: TMVCJsonDataObjectsSerializer;
  47.   j: TJsonObject;
  48.   oo: TObjC;
  49. begin
  50.   s := '{"PropStr":"This is a value", "ObjA": {"Y": "Hello There","ObjB": null,"X": null}}';
  51.   j := TMVCJsonDataObjectsSerializer.ParseObject(s);
  52.   oo := TObjC.Create;
  53.   oo.ObjA := nil;
  54.   lSer := TMVCJsonDataObjectsSerializer.Create;
  55.   lSer.JsonObjectToObject(j, oo, stProperties, []);
  56.  
  57.   //"oo.ObjA" has not been instantiated, it is still null
  58.  
  59.   if (not Assigned(oo.ObjA)) and (not j.IsNull('ObjA')) then
  60.   begin
  61.     oo.ObjA := TObjA.Create;
  62.     lSer.JsonObjectToObject(j.O['ObjA'], oo.ObjA, stProperties, []);
  63.   end;
  64.  
  65.   if oo.ObjA = nil then
  66.   begin
  67.     WriteLn('ObjA is nil');
  68.   end
  69.   else
  70.   begin
  71.     WriteLn('String Value is: ', oo.PropStr);
  72.     WriteLn('oo.ObjA.Y is: ', oo.ObjA.Y.ValueOrDefault);
  73.   end;
  74. end;
  75.  
  76.  
  77. begin
  78.   Test;
  79. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement