On 21/07/2011 08:57, Tobias Pankrath wrote:
Hi everyone,
I'm taking a look at D again and asked myself, if
it is possible to write a template mixin or something
similiar that automatically serializes an object to json.
For example:
class MyClass
{
string memberA;
int memberB;
MyClass memberC;
mixin ToJson!MyClass;
}
should make possible to automatically output
"someid" { "memberA" : "somestring",
"memberB" : 12,
memberC : "someotherid"};
How could this be accomplished? I've found std.traits
RepresentationTypeTupel but don't see how this would
help me.
Thanks,
Tobias
Something like this is very possible, here's a start for you (untested,
sorry about the awkward indentation):
----
mixin template ToJson(T)
{
string toJson()
{
foreach (i, member; T.tupleof)
{
enum memberName = T.tupleof[i].stringof[
T.stringof.length + 3 .. $
];
writefln("%s : %s", memberName, member);
}
assert(0, "Eventually this should return a json string, "
"but for now it just asserts");
}
}
someInstanceOfMyClass.toJson();
----
I'll leave it at this and leave you to figure out the rest - just ask if
you get stuck :)
--
Robert
http://octarineparrot.com/