Databases, MongoDB included have a concept of a null value. Unfortunately value types in D do not. D has a standard way of creating a nullable value in std.typecons.

Looking at the serialization code in vibe, the only way to work with null values is to use classes. However, in the project I am porting I rely on null to work out if a user has set a boolean type or not. Take this example:

struct User {
    bool subscribed;
}

I ideally I would like to know if the user has subscribed, unsubscribed or hasn't answered at all. The simplest solution in D would be to use Nullable!bool as the the type. However the serialization framework doesn't support this.

My questions are twofold.

  • Is there a way I can retrofit this kind of serialization to work with my existing models without changing the core Vibe.d code?
  • Failing that, is there a reason we shouldn't modify the serialization code to recognise Nullable types?

Below I have unit tests which have a sample usage which I think would be ideal. Thanks in advance!

unittest {
	import std.typecons;
	import vibe.data.json;

	struct User {
		Nullable!bool subscribed;
	}

	User u;

	auto json = serializeToJson(u);
	assert(json.subscribed == Json.undefined);
}

unittest {
	import std.typecons;
	import vibe.data.json;

	auto json = Json.emptyObject;

	json.subscribed = Json.undefined;

	struct User {
		Nullable!bool subscribed;
	}

	User u;
	u.subscribed = true; // Set this so we can be sure the deserialize sets it back to null

	deserializeJson(u, json);
	assert(u.subscribed.isNull);
}