Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Object-Pascal / Delphi-Language (https://www.delphipraxis.net/32-object-pascal-delphi-language/)
-   -   TJsonObject kann kein Enum? (https://www.delphipraxis.net/201010-tjsonobject-kann-kein-enum.html)

Der schöne Günther 14. Jun 2019 18:06

Delphi-Version: 10 Seattle

TJsonObject kann kein Enum?
 
Stelle ich mich zu dumm an oder geht folgendes nicht?

Delphi-Quellcode:
program JsonToEnumProject;

uses
  System.SysUtils,
  System.Json;

type
   TEnum = (one, two, three);

const
   input = '{"enum": "two"}';
var
   jsonObject: TJSONObject;
   enum: TEnum;
begin
   jsonObject := (TJSONObject.ParseJSONValue(input) as TJSONObject);
   try
      // EJSONException: 'Conversion from TJSONString to TEnum is not supported'
      enum := jsonObject.GetValue<TEnum>('enum');
      Assert( enum = TEnum.two);
   finally
      jsonObject.Destroy();
   end;
end.
In
Delphi-Quellcode:
System.Json
sehe ich dass in der Routine
Delphi-Quellcode:
StrToTValue
bei einem enum es nicht einmal versucht wird. Ernsthaft? Ist das in aktuellen Delphi-Versionen immer noch so?

Falls ja, ich habe mir einen kleinen Helper gemacht. Wäre der so ok?

Delphi-Quellcode:
   function TJsonObjectHelper.GetValue<T>(const APath: string): T;
   var
      enumInfo: PTypeInfo;
      enumAsString: String;
      enumAsInteger: Integer;
   begin
      enumInfo := TypeInfo(T);
      if(enumInfo.Kind = TTypeKind.tkEnumeration) then
         begin
            enumAsString := GetValue<String>(APath);
            enumAsInteger := GetEnumValue(enumInfo, enumAsString);
            if(enumAsInteger <> -1) then
               Result := TValue.FromOrdinal(enumInfo, enumAsInteger).AsType<T>()
            else
               raise EJSONException.CreateFmt(SNoConversionAvailableForValue, [enumAsString, enumInfo.Name]);
         end
      else
         Result := inherited GetValue<T>(APath);
   end;
(https://gist.github.com/JensMertelme...72876e55009129)

Zacherl 14. Jun 2019 20:02

AW: TJsonObject kann kein Enum?
 
Ja, so toll die JSON Unterstützung in Delphi auch ist, meinen Ansprüchen ist sie damals auch nicht gerecht geworden. Wenn du JSON in der von dir gezeigten manuellen Art und Weise parsen willst, sind diese Klassen für dich vielleicht von Interesse:
https://github.com/flobernd/delphi-u...Utils.JSON.pas

Kurze Doku gibts auch:
https://github.com/flobernd/delphi-utils/wiki/JSON

Stevie 14. Jun 2019 20:30

AW: TJsonObject kann kein Enum?
 
Zitat:

Zitat von Der schöne Günther (Beitrag 1434666)
Ist das in aktuellen Delphi-Versionen immer noch so?

In 10.3 funktioniert das - aber die Mengen an Code, die dafür durchlaufen werden, sind echt gruselig :oops:


Alle Zeitangaben in WEZ +1. Es ist jetzt 04:16 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz