#1 2013-01-18 07:47:53

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

New optional "ClassName":"TMyClass" field in JSON object serialization

New TJSONSerializer.RegisterClassForJSON() methods have been introduced.

They allowing recognition of class types from a new

{"ClassName":"TMyObject",....

JSON field generated by ObjectToJSON(..[woStoreClassName]) new option.

This field will be recognized:
- by JSONToObject() for TObjectList members,
- and by the new JSONToNewObject() method.

Note that all TSQLRecord classes of a model are automaticaly registered.

This kind of code can now work:

// register the type (but we check also Classes.RegisterClass list)
TJSONSerializer.RegisterClassForJSON([TComplexNumber]);
// create an instance by reading the textual class name field
J := '{"ClassName":"TComplexNumber", "Real": 10.3, "Imaginary": 7.92 }';
P := @J[1]; // make local copy of constant
Comp := TComplexNumber(JSONToNewObject(P,Valid));
// here Comp is a valid unserialized object :)
Check(Valid);
Check(Comp.ClassType=TComplexNumber);
CheckSame(Comp.Real,10.3);
CheckSame(Comp.Imaginary,7.92);
// do not forget to free the memory (Comp can be nill if JSON was not valid)
Comp.Free;

See http://synopse.info/fossil/info/d02cc9e400

I have introduced this feature also to interface-based services.
See http://synopse.info/fossil/info/bf362a58d1

Offline

Board footer

Powered by FluxBB