Am 21.05.2016 um 23:33 schrieb Tomáš Chaloupka:

I'm accessing the API which have uppercase enum values, but I don't like them and so want to be able to deserialize them with case insensitive way.

This does not work:

enum Color {
	red,
	green,
	blue
}
	
struct Test {
	@byName Color color;
}

assert(deserializeJson!Test(Json(["color":Json("RED")])).color == Color.red);


I tried to implement custom policy, like this (there is not much documentation about it):

template UpperCasePolicy(S) {
	import std.conv, std.string : toLower, toUpper;

	S fromRepresentation(string value) {
		return value.toLower.to!S;
	}

	string toRepresentation(S value) {
		return to!string(value).toUpper;
	}
}
	
struct Test {
	@byName!UpperCasePolicy Color color;
}

But it ends up with the strange error: Got JSON of type string, expected int_, bigInt

I can't figure out what I'm doing wrong :(

Policy based serialization definitely needs a proper introduction. So
the right way to use it is to pass the policy to the
serializeWithPolicy function (which has the downside that this doesn't
always work in high-level scenarios, e.g. in the web/REST generators).
It would look similar to this:

template UpperCasePolicy(T) if (T == Color) {
     import std.conv, std.string : toLower, toUpper;

     Color fromRepresentation(string value) {
         return value.toLower.to!Color;
     }

     string toRepresentation(Color value) {
         return to!string(value).toUpper;
     }
}

struct Test {
     Color color;
}

Test test = {Color.red};

assert(test.serializeWithPolicy!(JsonStringSerializer, UpperCasePolicy)
     == `{"color":"RED"}`);
assert(`{"color": "GREEN"}`
     .deserializeWithPolity!(JsonStringSerializer, UpperCasePolicy, Test)
     == Test(Color.green));