Link to home
Start Free TrialLog in
Avatar of Allan_Fernandes
Allan_Fernandes

asked on

JSON on ISAPI REST Server using Delphi

When I create JSON thru a REST server (ISAPI) using Delphi I get

{"result":["{\"books\":[{\"FLD_CODE\":\"1010\",\"FLD_NAME\":\"Allan\",\"FLD_MOBILE\":\"986701\",\"FLD_EMAILID\":\"allan@test.som\",\"FLD_ADDDATE\":\"01\/01\/16\",\"FLD_EDITDATE\":\"01\/01\/16\",\"FLD_TIMESCONNECTED\":\"99\",\"FLD_LASTJPG_VERSION\":\"1\"}]}"]}

Open in new window


When I create JSON thru a VCL Delphi application I get

{"books":[{"FLD_CODE":"1010","FLD_NAME":"Allan","FLD_MOBILE":"986701","FLD_EMAILID":"allan@ssmic.om","FLD_ADDDATE":"01/01/16","FLD_EDITDATE":"01/01/16","FLD_TIMESCONNECTED":"99","FLD_LASTJPG_VERSION":"1"}]}

Open in new window


Parsing the latter output works fine and former gives Access violation


Logic used to Create JSON
var
  jStr:String ;
  o: TJSONObject;
  a: TJSONArray;
  book: TJSONObject;
  idx: integer;
  idy: integer;
begin
    o := TJSONObject.Create;
    a := TJSONArray.Create();
    o.AddPair('books',a);
    book := TJSONObject.Create;
    book.AddPair(TJSONPair.Create('FLD_CODE', '1010') );
    book.AddPair(TJSONPair.Create('FLD_NAME', 'Allan') );
    book.AddPair(TJSONPair.Create('FLD_MOBILE', '999999') );
    book.AddPair(TJSONPair.Create('FLD_EMAILID', 'allan@test.som') );
    book.AddPair(TJSONPair.Create('FLD_ADDDATE', '01/01/16' ) );
    book.AddPair(TJSONPair.Create('FLD_EDITDATE', '01/01/16' ) );
    book.AddPair(TJSONPair.Create('FLD_TIMESCONNECTED', '99') );
    book.AddPair(TJSONPair.Create('FLD_LASTJPG_VERSION', '1') );
    a.AddElement(book);
    memo1.text:=o.ToString ;

Open in new window


Logic used to Parse JSON
var
  jStr:String ;
  o: TJSONObject;
  a: TJSONArray;
  book: TJSONObject;
  idx: integer;
  idy: integer;
begin
  o := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(memo1.text),0) as TJSONObject;
  try
    a := TJSONArray(o.Get('books').JsonValue);
    for idx := 0 to pred(a.size) do begin
      book := TJSONObject(a.Get(idx));
      for idy := 0 to pred(book.Count) do begin
        ShowMessage( book.Pairs[idy].JsonString.ToString + ':' + book.Pairs[idy].JsonValue.ToString );
      end;
    end;
  finally
    o.Free;
  end;

Open in new window

Avatar of aikimark
aikimark
Flag of United States of America image

The \" character sequences area way to encode the JSON string, such that imbedded quotes (within strings) do not confuse the parser.  In this case you might try to do a replace of \" with " and see if the parser is any happier.

Of course, that is only a safe thing to do if your data strings won't contain any embedded quote characters.
ASKER CERTIFIED SOLUTION
Avatar of aikimark
aikimark
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial