Recent

Author Topic: [SOLVED] MemoryStream creates bad JSON file  (Read 1510 times)

JD

  • Hero Member
  • *****
  • Posts: 1848
[SOLVED] MemoryStream creates bad JSON file
« on: September 29, 2018, 08:44:05 pm »
Hi there everyone,

I am using Visual Planit and its VpJSONDataStore to create a JSON agenda. VpJSONDataStore reads the JSON file from the disk but since my data comes from a remote server, I am compelled to save it to disk first before the VpJSONDataStore can read it.

Here is the code I use to create the data.json file:

Code: Pascal  [Select][+][-]
  1. //
  2. AStream     := TMemoryStream.Create;
  3. //
  4. try
  5.   AStream.WriteAnsiString(Trim(AData)));
  6.   AStream.Position := 0;
  7.   AStream.SaveToFile('data.json');
  8. finally
  9.   AStream.Free;
  10. end;
  11.  

The problem is that the data.json file created has some extra characters at the beginning of the file (see RED ARROW in the screenshot). I am certain that the JSON is correct in the AData string variable.

Does anyone know how I can correct this problem?

Thanks,

JD

« Last Edit: September 29, 2018, 09:31:34 pm by JD »
Windows - Lazarus 2.1/FPC 3.2 (built using fpcupdeluxe),
Linux Mint - Lazarus 2.1/FPC 3.2 (built using fpcupdeluxe)

mORMot; Zeos 8; SQLite, PostgreSQL & MariaDB; VirtualTreeView

fred

  • Full Member
  • ***
  • Posts: 201
Re: MemoryStream creates bad JSON file
« Reply #1 on: September 29, 2018, 08:56:07 pm »
WriteString first writes the string length "The ansistring is written as a 4 byte length specifier, followed by the ansistring's content."

https://www.freepascal.org/docs-html/rtl/classes/tstream.writeansistring.html

I suppose you need WriteBuffer(AData[1], Length(AData))
« Last Edit: September 29, 2018, 08:58:47 pm by fred »

JD

  • Hero Member
  • *****
  • Posts: 1848
Re: MemoryStream creates bad JSON file
« Reply #2 on: September 29, 2018, 09:06:34 pm »
WriteString first writes the string length "The ansistring is written as a 4 byte length specifier, followed by the ansistring's content."

https://www.freepascal.org/docs-html/rtl/classes/tstream.writeansistring.html

I suppose you need WriteBuffer(AData[1], Length(AData))

Perfect. Thanks a lot  :D

JD
Windows - Lazarus 2.1/FPC 3.2 (built using fpcupdeluxe),
Linux Mint - Lazarus 2.1/FPC 3.2 (built using fpcupdeluxe)

mORMot; Zeos 8; SQLite, PostgreSQL & MariaDB; VirtualTreeView

 

TinyPortal © 2005-2018