Skip to content

Instantly share code, notes, and snippets.

@Overv
Last active January 2, 2016 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Overv/8282615 to your computer and use it in GitHub Desktop.
Save Overv/8282615 to your computer and use it in GitHub Desktop.
Convert any D type to JSON automatically through trait/template magic
import std.stdio;
import std.conv;
import std.array;
import std.traits;
class Foo {
Bar nested;
this(Bar nested) {
this.nested = nested;
}
}
class Bar {
string data;
this(string data) {
this.data = data;
}
}
string json(T) (T obj) {
static if (is(typeof(obj) == string)) {
return "\"" ~ obj.replace("\\", "\\\\").replace("\"", "\\\"") ~ "\"";
} else static if (isBasicType!(typeof(obj))) {
return to!string(obj);
} else {
string res = "";
foreach (mem; __traits(allMembers, typeof(obj))) {
static if (!isCallable!(__traits(getMember, obj, mem)) && __traits(compiles, json(__traits(getMember, obj, mem)))) {
auto val = __traits(getMember, obj, mem);
res ~= "\"" ~ mem ~ "\":" ~ json(val) ~ ",";
}
}
if (res.length > 0) res = res[0..$-1];
return "{" ~ res ~ "}";
}
}
void main() {
Foo obj = new Foo(new Bar("Hello, world!"));
writeln(json(obj));
}
@Overv
Copy link
Author

Overv commented Jan 6, 2014

Output:

{"nested":{"data":"Hello, world!"}}

@handsomematt
Copy link

give me the d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment