AGB  ·  Datenschutz  ·  Impressum  







Anmelden
Nützliche Links
Registrieren
Thema durchsuchen
Ansicht
Themen-Optionen

Wie aus diesem JSON object erstellen?

Ein Thema von Hobbycoder · begonnen am 14. Mai 2020 · letzter Beitrag vom 15. Jul 2021
 
Der schöne Günther

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

AW: Wie aus diesem JSON object erstellen?

  Alt 14. Mai 2020, 08: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 08:32 Uhr)
  Mit Zitat antworten Zitat
 


Forumregeln

Es ist dir nicht erlaubt, neue Themen zu verfassen.
Es ist dir nicht erlaubt, auf Beiträge zu antworten.
Es ist dir nicht erlaubt, Anhänge hochzuladen.
Es ist dir nicht erlaubt, deine Beiträge zu bearbeiten.

BB-Code ist an.
Smileys sind an.
[IMG] Code ist an.
HTML-Code ist aus.
Trackbacks are an
Pingbacks are an
Refbacks are aus

Gehe zu:

Impressum · AGB · Datenschutz · Nach oben
Alle Zeitangaben in WEZ +1. Es ist jetzt 13:20 Uhr.
Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024-2025 by Thomas Breitkreuz