[fpc-pascal] JSON register new data types for custom output/input
Michael Van Canneyt
michael at freepascal.org
Tue May 17 14:01:35 CEST 2016
On Tue, 17 May 2016, Graeme Geldenhuys wrote:
> On 2016-05-17 12:23, Michael Van Canneyt wrote:
>> There cannot be custom output in JSON, then it would no longer be JSON.
>> JSON is a fixed defined format; it does not allow "deviation".
>
> Maybe you understood me wrong, or my output examples were rubbish - you
> pick. ;-) I don't mean generating non-standard JSON output. The output
> will still be true JSON, just in a improved format for multiple
> applications (not just FPC or Delphi based) to understand.
>
> eg:
> Here is a snippet of a JavaScript based Report Designer that outputs
> colour values to JSON:
>
> "Brush": "solid:77,182,172",
> "TextBrush": "solid:255,255,255",
>
> Note, it is still valid JSON, but it is an improved output format that
> most likely multiple application could understand better than the
> original TColor value.
>
> Now obviously I can manually format TColor to the above string output,
> and than parse the string data when read again. I would have to do this
> at all places where I save/read a TColor value.
>
> My suggestion is if one could register a TColor reader/writer type, and
> fpjson can then do the rest - using the helper classes when needed. I
> would only have to register this new type once in my application, and
> persisting TColor could be simpler in my code.
>
> Granted, I haven't given this much thought - it's just an idea that
> popped up. So there is most likely some details or usage idea that need
> to be worked out.
>
>
> Another useful example would be persisting enum types. Currently I have
> to write functions like StretchTypeToString() and StringToStretchType()
> and then use these all over my code where I read/write a TStretchType
> value. I'm hoping the above idea could simplify code like this too.
JSONRTTI, RestBase or WST do all this for you. It takes care of enumerateds
objects, arrays etc.
JSONRTTI, RestBase can easily be enhanced to support a custom type registry:
RegisterType(TypeInfo(TMySpecialType), @Reader, @Writer)
Where reader and writer are defined along the lines of:
AReader = Procedure (Instance : TObject; AProperty: PPropInfo; Data : TJSONData) of Object;
AWriter = Function (Instance : TObject; AProperty: PPropInfo) : TJSONData of object;
or so.
Michael.
More information about the fpc-pascal
mailing list