On 03/21/2013 01:34 PM, Dan wrote: > Json serializeToJson(T)(T value) { > ... > static if( __traits(compiles, value = T.fromJson(value.toJson())) ){
It looks like fromJson must be a static member function because the condition is written in a way that fromJson is called on the type itself. (I don't know any trick to bind that to a regular function.)
It may not be suitable in your case but wrapping the enum inside a struct is a solution (struct AssetCategory below):
import std.stdio; import std.conv; struct Json { string s; this(string s) { writefln("constructing with %s", s); this.s = s; } T opCast(T : string)() const { return s; } } Json serializeToJson(T)(T value) { static if( __traits(compiles, value = T.fromJson(value.toJson())) ) { return value.toJson(); } else { return Json("NOT GOOD: DEFAULT BEHAVIOR"); } } enum AssetCategoryType { Investment, PrimaryResidence, FamilyProperty, FinancialInstrument } struct AssetCategory { AssetCategoryType assetType; alias assetType this; static AssetCategory fromJson(Json src) { string value = cast(string)src; return AssetCategory(value.to!AssetCategoryType); } } static Json toJson(AssetCategory assetType) { auto result = Json(); result = Json(text(assetType)); return result; } void main() { auto category = AssetCategory(AssetCategoryType.FamilyProperty); auto json = serializeToJson(category); writeln(json); // Test fromJson assert(AssetCategory.fromJson(Json("PrimaryResidence")) == AssetCategory(AssetCategoryType.PrimaryResidence)); } Ali