#1 2013-01-14 21:51:47

arquivo59
Member
Registered: 2013-01-14
Posts: 24

ObjectToJSON

Hi, sorry about my English, I'm from Brazil.

I'm trying to turn a Object into JSON format putting the result into a TMemo. Its a simple class:

  TCostumer = class(TPersistent)
  private
    FName: RawUTF8;
  public
    property Name: RawUTF8 read FName write FName;
  end;

The code I'm using is:

 procedure TForm1.Button1Click(Sender: TObject);
var
  c : TCostumer ;
begin
  c := TCostumer .Create;
  c.Name:= 'Tom';
  Memo1.Lines.Add(ObjectToJSON(c));
end;

The problem is that the result is "{}". What am I doing wrong?

Last edited by arquivo59 (2013-01-14 21:54:07)

Offline

#2 2013-01-14 22:01:58

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,659
Website

Re: ObjectToJSON

You need to define your properties as PUBLISHED, not public.

Offline

#3 2013-01-14 22:52:24

arquivo59
Member
Registered: 2013-01-14
Posts: 24

Re: ObjectToJSON

Perfect, thank you.

How do I use de function JSONToObject?

JSONToObject(d, Putf8char(mmo1.Lines.Text), b);

d is a TCostumer, mmo1.Lines.Text has the JSON from the result of the earlier procedure, and b is a boolean.

However the code:

mmo1.Lines.Add(d.Name);

Results in a empty string ''.

Offline

#4 2013-01-15 09:36:11

mpv
Member
From: Ukraine
Registered: 2012-03-24
Posts: 1,571
Website

Re: ObjectToJSON

In your example mmo1.Lines.Text is string type. But JSONToObject need RawUTF8 as input parameter. RawUTF8 is UTF-8 encoded string, so direct conversoin Putf8char(mmo1.Lines.Text) is not allowed!
So please, read comments in interface part of mORMot.pas where function JSONToObject defined.
In your case correct code is:
var
  R: RawUTF8;
  isValid: boolean;

R := StringToUTF8(mmo1.Lines.Text); // !! IMPORTANT to put Text into buffer (R) and perform conversion from string to RawUTF8!!!
JSONToObject(d, PUTF8Char(R), isValid);
if isValid then
  mmo1.Lines.Add(d.Name)
else
  mmo1.Lines.Add('invalid JSON string');

Offline

Board footer

Powered by FluxBB