How to serialize a Json in Object? Delphi XE7

Asked

Viewed 1,421 times

1

I need to generate an Object that represents a JSON file and Delphi is generating me the following

ERROR: 'Internal: Invalid pair name {"directory":"d: Folder Doc"}: expected type or ref'

In the code line:

  objetoJson := UnMar.UnMarshal(oJson) as TJson;

Would someone please tell me what the problem is and how to fix it?

program Project2;

{$APPTYPE CONSOLE}

{$R *.res}

uses   System.SysUtils, Data.DBXJSONReflect, JSON;

type
  TJson = CLass
    diretorio: string;
  end;

var
  oJson: TJSONObject;
  objetoJson: TJson;
  UnMar: TJSONUnMarshal;
begin
  try
// Crio o Json
oJson := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes('{"diretorio": "d:\\Pasta\\Doc"}'),0) as TJSONObject;
// Mostra o conteudo no Json no console
Writeln('Conteudo do objeto Json: '+ojson.ToString);
UnMar := TJSONUnMarshal.Create;
try
  // Tento repassar o Objeto de Json para a Classe
  objetoJson := UnMar.UnMarshal(oJson) as TJson;
  try
    writeln(  objetoJson.diretorio);

  finally
    objetoJson.Free;
  end;
finally
  UnMar.Free;
end;
  except
on E: Exception do
begin
  Writeln('Erro ao tentar usar UmMarshal: ');
  Writeln( E.Message);
end;
  end;
  readln;
end.

1 answer

1


Objects in Pascal Object are typed, so you need to include some references within the JSON so that the process of UnMarshal can identify the ID and the REF.

Here is an example of JSON that should be passed:

'{"type":"Project2.TJsonOBJ","id":1,"fields":{"diretorio":""}}'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.