dkounal 3 Posted December 2, 2020 (edited) 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 December 2, 2020 by dkounal Share this post Link to post
FPiette 383 Posted December 3, 2020 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
Der schöne Günther 316 Posted December 3, 2020 Or another library, like paolo-rossi/delphi-neon: JSON Serialization library for Delphi (github.com) 2 Share this post Link to post
dkounal 3 Posted December 3, 2020 18 minutes ago, Der schöne Günther said: Or another library, like paolo-rossi/delphi-neon: JSON Serialization library for Delphi (github.com) Thank you very much. I have noticed this library in the past but I did not remember it supports records too. Share this post Link to post
mvanrijnen 123 Posted December 3, 2020 I like this one a lot: Efficient and easy-to-use JSON and BSON library – grijjy blog 1 Share this post Link to post
dkounal 3 Posted December 3, 2020 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: I like this one a lot: Efficient and easy-to-use JSON and BSON library – grijjy blog Share this post Link to post