Einzelnen Beitrag anzeigen

Der schöne Günther

Registriert seit: 6. Mär 2013
6.093 Beiträge
 
Delphi 10 Seattle Enterprise
 
#2

AW: Wie aus diesem JSON object erstellen?

  Alt 14. Mai 2020, 09:28
Du hast dir deine Antwort doch schon selbst gegeben, es ist ein Objekt.

Die in der Delphi RTL vorhandene JSON-Serialisierung geht auf die Felder, nicht auf die Properties. Außerdem setzt sie zwingend voraus dass jeder Mensch die Namen der Felder immer mit einem F beginnt. Tust du das nicht, funktioniert es nicht. Oder man sagt explizit mit einem Attribut dass man es ernst meint.

Delphi-Quellcode:
unit Unit1;

interface uses Rest.JSON.Types;

type
   TUserAttributes = class
      [JSONName('notificationTokens')]
      notificationTokens: String;
      [JSONName('color.background')]
      color_background: String;
   end;

   TUser = class
      [JSONName('id')]
      id: Integer;
      [JSONName('attributes')]
      attributes: TUserAttributes;
      [JSONName('name')]
      name: string;
      [JSONName('login')]
      login: string;
      [JSONName('email')]
      email: string;

      constructor Create();
      destructor Destroy(); override;
   end;

implementation

constructor TUser.Create();
begin
   inherited;
   attributes := TUserAttributes.Create();
end;

destructor TUser.Destroy();
begin
   attributes.Free();
   inherited;
end;

end.


Das lässt sich herrlich hin- und her konvertieren:

Delphi-Quellcode:
program Project1;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.JSON,
  Rest.Json,
  Unit1 in 'Unit1.pas';

const
   input =
      ' {'+
      ' "id":1,'+
      ' "attributes":{'+
      ' "notificationTokens":"bliblablup",'+
      ' "color.background":"#yellow"'+
      ' },'+
      ' "name":"admin",'+
      ' "login":"",'+
      ' "email":"admin"'+
      ' }';
var
   user: TUser;
   asJsonObject: TJsonObject;
begin
   user := TJson.JsonToObject<TUser>(input);
   asJsonObject := TJson.ObjectToJsonObject(user);
   WriteLn( TJson.Format(asJsonObject) );

   readln;
end.

Geändert von Der schöne Günther (14. Mai 2020 um 09:32 Uhr)
  Mit Zitat antworten Zitat