Skip to content

Instantly share code, notes, and snippets.

@omonien
Last active January 31, 2022 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omonien/71353c3f91ea88b36b0a9ff5f64f377e to your computer and use it in GitHub Desktop.
Save omonien/71353c3f91ea88b36b0a9ff5f64f377e to your computer and use it in GitHub Desktop.
program JsonNaming;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.Classes,
System.SysUtils,
REST.Json,
REST.Json.Types,
JsonNaming.Foo in 'JsonNaming.Foo.pas';
begin
try
// ommiting proper memory management here for simplicity
var LFoo := TFoo.Create;
LFoo.Bar := 'Bar';
LFoo.Name := 'Foo';
// Object to Json
var LFooJson := TJson.ObjectToJsonString(LFoo);
Assert(LFooJson = '{"bar":"Bar","FName":"Foo"}');
// Json to Object
LFoo := TJson.JsonToObject<TFoo>(LFooJson);
Assert(LFoo.Bar = 'Bar');
Assert(LFoo.Name = 'Foo');
except
on E: Exception do
writeln(E.ClassName, ': ', E.Message);
end;
end.
unit JsonNaming.Foo;
interface
uses
System.Classes, System.SysUtils,
REST.Json.Types;
type
TFoo = class(TObject)
private
// Default naming strategy: cutting off leading "F", and making it lowerCamelCase
FBar: string;
// Custom naming
[JSONName('FName')]
FName: string;
public
property Bar: string read FBar write FBar;
property Name: string read FName write FName;
end;
implementation
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment