Jump to content
dkounal

I can serialize a record but I can not deserialize

Recommended Posts

I need to serialize and de-serialize different records types.

I wrote the following code that works ok only for the serialization and to be honest, I have not tested having records with class objects.

The opposite, the de-serialization gives me an error " Internal: Cannot instantiate type .... " when calling the TJson.JsonToObject. I believe it has to do with the initialization of the new object but I can not understand the problem

Any ideas? Thank you in advance

The code is:

type Trec4Json<T>=class
   private
     fbv:T;
   public
     class Function rec2J(a: T):string;
     class Function J2rec(const a: string; var c:T):boolean;
     property bv:T read fbv write fbv;
end;


implementation
uses rest.json;

{ Trec4Json<T> }

class function Trec4Json<T>.rec2J(a: T): string;   // Record to Json String
var
  b: Trec4Json<T>;
begin
  b := Trec4Json<T>.create;
  b.bv := a;
  try
    result := TJson.ObjectToJsonString(b);
  finally
    b.free;
  end;
end;

class function Trec4Json<T>.J2rec(const a: string; var c: T): boolean;   // Json String to Record
var
  b: Trec4Json<T>;
begin
  try
    b := TJson.JsonToObject < Trec4Json < T >> (a);
    c := b.bv;
    b.free;
    result := true;
  except
    result := false;
  end;
end;

 

Edited by dkounal

Share this post


Link to post
11 hours ago, dkounal said:

the de-serialization gives me an error " Internal: Cannot instantiate type .... " when calling the TJson.JsonToObject.

Use a class instead of a record.

Share this post


Link to post

To be honest I usually use the above rec2J to log records with the Codesite express.

Now, I need to transfer different type of records in JSON through mqtt protocol. So, I was investigating the J2rec.

The idea of using BSON for the mqtt seems also better. Thank you a lot

1 hour ago, mvanrijnen said:

 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×