Writing JSON

First let's look at different ways of generating JSON. We will save this information to a file and later we will read this information back into a local favorites list.

Again we are going to start with implementing a GetFilename function, but this time to write and read from the favs.json file:

function TFormFavJSON.GetFilename: string; begin   Result := TPath.Combine(TPath.GetDocumentsPath, 'favs.json'); end; 

We will also need a simple function to write a string with JSON text to a file. It is so simple with the TStreamWriter class that we saw earlier. Refer to the following code snippet:

procedure TFormFavJSON.WriteJsonTextToFile(txt: string); var sw: TStreamWriter; begin  sw := TStreamWriter.Create(GetFilename, False, TEncoding.UTF8); ...

Get Expert Delphi now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.