Home > Blockchain >  TJSON.JsonToObject<classname> not working in Delphi
TJSON.JsonToObject<classname> not working in Delphi

Time:03-27

I am trying to convert Json trying to class object, but the values are not appearing in the new object variable. The resulting object has blank value in string and 0 in integer. Thanks in advance.

Code:

type
Student =class
    public
    Name : string;
    Age : Integer;
end;

procedure TForm2.Button5Click(Sender: TObject);
var
  Student1, Student2: Student;
  STR: string;
begin
  Student1 := Student.Create;
  Student2 := Student.Create;

  try
  Student1.Name := 'Sam';
  Student1.Age := 24;
  str := TJson.ObjectToJsonString(Student1);
  Form2.outputMemo.Lines.Add(str);
  Student2 := TJSON.JsonToObject<Student>(str);
  Form2.outputMemo.Lines.Add(Student2.Name);
  Form2.outputMemo.Lines.Add(Student2.Age.ToString);
  finally
  Student1.Free;
  Student2.Free;
  end;
//Form2.outputMemo.Lines.Text :=TJson.ObjectToJsonObject(Student1);

end;

Output:

{"name":"Sam","age":24}

0

Edit: I just saw this, and it worked when I changed the names to FName and FAge... what a sorcery!, can anyone please explain the logic behind this? delphi-rest-json-jsontoobject-only-works-with-f-variables

CodePudding user response:

The internal mapping of JSON fields to Delphi fields is prefixing them with F and changing the following character to upper case. If you want complete control over this you can specify the JSON name with an attribute:

type
  Student =class
  public
    [JSONName('name')]
    Name : string;
    [JSONName('age')] 
    Age : Integer;
  end;

Note that the JSON names given are case sensitive.

You need to include REST.Json.Types to the uses so that the attribute declaration can be found.

  • Related