Schlagwort-Archive: ObjectMapper

Delphi 10.1 Berlin Starter and DMVCFramework – ObjectMapper

After testing the DMVC Framework with Delphi 10.1 Berlin Starter (see my previous post) I have tested the ObjectMapper. First: It works. The following code will convert the JSON data into Delphi objects:

uses
  ObjectsMappers;

//first "download" the data and write it to a Memo
//note the change of the url "/maps/api/geocode/json" instead of "/maps/api/geocode/xml"
procedure TForm1.Button2Click(Sender: TObject);
var
  Clt: TRestClient;
begin
  Clt := MVCFramework.RESTClient.TRESTClient.Create('http://maps.googleapis.com', 80, nil);
  try
    Memo1.Lines.Text := Clt.doGET('/maps/api/geocode/json?address=Berlin', []).BodyAsString;
  finally
    Clt.Free;
  end;
end;

procedure TForm1.Button3Click(Sender: TObject);
var
  Root: TRootObject;
  I, J: Integer;
begin
  //use the Mapper to convert the string into a real Delphi object
  Root := Mapper.JSONObjectStringToObject<TRootObject>(Memo1.Lines.Text);
  try
    Memo2.Lines.Clear;
	//use the object like a normal Delphi object
    Memo2.Lines.Add('Status: ' + Root.Status);
    for I := 0 to Root.Results.Count - 1 do
    begin
      Memo2.Lines.Add('Formatted_Address: ' + Root.Results[I].Formatted_Address);
      for J := 0 to Root.Results[I].Address_Components.Count - 1 do
      begin
        Memo2.Lines.Add('  ' + Root.Results[I].Address_Components[J].Long_Name);
      end;
    end;
  finally
    Root.Free;
  end;
end;

//this code will also work:
//Root := Clt.doGET('/maps/api/geocode/json?address=Berlin', []).BodyAsJSONObject.AsObject<TRootObject>;

Weiterlesen