#1 2017-08-15 08:27:56

mustbe2
Member
Registered: 2017-08-15
Posts: 2

Unable to get ObjectToJSON working.

Hi,

Im new to Delphi and i am assiged to webenable the Delphi project here. We like to connect my C# ASP services to the Delphi program.

In my code below ObjectToJSON works, but not the opposite way; so no object is created or filled with the JSONContent. What ami i doing wrong.

Thanks smile


unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,  Vcl.Controls, Vcl.Forms, Vcl.Dialogs,  generics.collections, mORMot, mORMotSQLite3, SynSQLite3Static, mORMotHttpServer, SynCommons, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  SampleClass = class(TSynPersistent)
  private
    Fstr: string;
    Fn: integer;
  published
    property Str: String read Fstr write Fstr;
  published
    property n: integer read Fn write Fn;
  end;

var
  Form1: TForm1;
  c: SampleClass;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  JSONContent: string;
  newObj: SampleClass;
  utf8: PUTF8char;
  JsonResult: boolean;

begin
  c := SampleClass.Create;
  c.Str := 'String';
  c.n := 99;
  JSONContent := ObjectToJSON(c);
  Memo1.lines.Add(JSONContent);

  newObj := SampleClass.Create;
  TJSONSerializer.RegisterClassForJSON(SampleClass);
  utf8 := JSONToObject(newObj, pointer(JSONContent), JsonResult, SampleClass, [j2oSetterNoCreate]);

  Memo1.lines.Add('JSONToObject result: ' + JsonResult.ToString);
  // JsonResult is false here, newObj is not filled.

  JSONContent := ObjectToJSON(newObj);
  Memo1.lines.Add(JSONContent)
end;

end.

Last edited by mustbe2 (2017-08-15 14:07:00)

Offline

#2 2017-08-16 06:41:05

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

Re: Unable to get ObjectToJSON working.

Take a look at your compiler messages.
You have hints about implicit string conversions...
And in fact, you use JSONContent: string then use pointer(JSONContent).
So you supply an UTF-16 content into JSONToObject(), which expect UTF-8 content.

As clearly stated by the documentation, and ensured by the parameter types, use RawUTF8 everywhere within your business code, to avoid such errors.

Offline

#3 2017-08-17 06:50:07

mustbe2
Member
Registered: 2017-08-15
Posts: 2

Re: Unable to get ObjectToJSON working.

Thanks, didn't see the warnings. Works now.

Offline

Board footer

Powered by FluxBB