static functions associated with enums

Dan dbdavidson at yahoo.com
Thu Mar 21 13:34:11 PDT 2013


I have an enum, say:

enum AssetCategory {
   Investment,
   PrimaryResidence,
   FamilyProperty,
   FinancialInstrument
}

and I have functions that convert to/from strings to be used in 
Json (via vibe json). The vibe wants to call out to user supplied 
toJson/fromJson if both functions are provided and the test for 
it is:

Json serializeToJson(T)(T value) {
...
  static if( __traits(compiles, value = 
T.fromJson(value.toJson())) ){
    return value.toJson();
...
}

I would like to use this feature to have the json output the 
string instead of numeric value (while still retaining numeric 
value in data structures). The toJson/fromJson functions below 
are close. They allow for this:

if( __traits(compiles, t.fromJson(t.toJson()) ))

to be true - but that is not the same thing. Is there a trickery 
to associate a static function with an enum? (e.g. 
AssetCategory.fromJson(json)) )

Thanks
Dan
-----------

static void fromJson(ref AssetCategory assetType, Json src) {
   string value = cast(string)src;
   writeln("value is ",value);
   final switch(value) {
   case "Investment": { assetType = AssetCategory.Investment; 
break; }
   case "PrimaryResidence": { assetType = 
AssetCategory.PrimaryResidence; break; }
   case "FamilyProperty": { assetType = 
AssetCategory.FamilyProperty; break; }
   case "FinancialInstrument": { assetType = 
AssetCategory.FinancialInstrument; break; }
   }
}

static Json toJson(AssetCategory assetType) {
   auto result = Json();
   result = text(assetType);
   return result;
}


More information about the Digitalmars-d-learn mailing list