Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TJSON.JsonToObject do not pass through setters

I'm with some problems when converting a Json string into a Object of my own. I'll give some example:

My class:

  TClasse = class
  private
    Fid: integer;
    Fnome: string;
    procedure Setid(const Value: integer);
    procedure SetNome(const Value: string);
  published
    property id : integer read Fid write Setid;
    property nome : string read Fnome write SetNome;
  end;

implementation

procedure TClasse.SetNome(const Value: string);
begin
  Fnome := Value;
  Fnome := 'testing: '+Fnome;
end;

I use that method:

  cl := TJSON.JsonToObject<TClasse>('{ "id" : 12, "nome" : "abc" }');

This means that when the method "JsonToObject" is executed, he will instance my class and set the values to then, passing through the setters. The property "nome" it should have the value "testing: abc", but it has only the "abc" part, from the json. Debugging also do not pass through the setters.

Am i doing something wrong?

like image 668
Guilherme Henrique Avatar asked Feb 27 '26 19:02

Guilherme Henrique


1 Answers

You could create a new class e.g. TJSON_Respond to help the serialization

TJSON_Respond= class
  public
    [JSONName('id')] id: Integer;
    [JSONName('nome')] nome: String;
  end;

cl := TJson.JSONToObject<TJSON_Respond>('{ "id" : 12, "nome" : "abc" }');
like image 91
MaGiC Avatar answered Mar 01 '26 08:03

MaGiC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!