Forum > Databases

Read and write objects to SQLite database

(1/2) > >>

A few months ago I started using free pascal for cgi scripts on the Gemini protocol.

I am making an app but have a need to read/write objects, such as TDictionary to/from sqlite.

I can get TStringList to export csv, but more complex objects don't seem obvious. I've searched the wiki, looked for methods and units, and searched here in the forum but couldn't find anything applicable.

In python the answer was JSON, but I don't see a similar function to load/dump objects to/from JSON in Free Pascal.

Thanks for any help.

You need to include e.g.: 'fpjson' amo, in your uses clause...
There are lots of json-related stuff in there.
Path = "...fpcsrc/packages/fcl-json/src/"
excerpt from readme.txt:
--- Quote ---This package implements JSON support for FPC.

You might want to have a look at the lazarus jsonviewer tool, written using
fpJSON (see lazarus/tools/jsonviewer). It visualizes the fpJSON data and
shows how to program using fpjson.

JSON support consists of 3 parts:

unit fpJSON contains the data representation. Basically, it defines a set of

+- TJSONNumber
   +- TJSONIntegerNumber
   +- TJSONFloatNumber
   +- TJSONInt64Number
+- TJSONString
+- TJSONBoolean
+- TJSONNull
+- TJSONObject
+- TJSONArray

--- End quote ---
Regards Benny

You can use RTTI to do this.
FPC has a unit fpjsonrtti that works well with objects and collections. Currently, only published properties are supported.
An example is attached.

Another solution, provided your objects are derived from TPersistent, which is compiled in $m+ state, is simply to use the default object streaming mechanism, which is a built-in (Read/WriteComponentResFile). I have been using that for 10's of years, actually since early Delphi. everybody seems to forget that mechanism.
But Benny is right: if you require JSON you can also do that in FreePascal, there are multiple good json libraries for fpc, fpjson is the default and good.
Paweld option is similar to the above, but json format.

Thank you for the quick responses and example.  I will check out fpjsonrtti.


[0] Message Index

[#] Next page

Go to full version