Convert any object to Json with Ceylon
import ceylon.json { Object, Array, Value, nil }
import ceylon.language.meta { type }
shared Value jsonValueOf<Source>(Source source)
given Source satisfies Anything {
switch (source)
case (is Null) { return nil; }
case (is String|Integer|Float|Boolean) { return source; }
else {
if (is {Anything*} source) {
return Array { for (element in source) jsonValueOf(element) };
}
// Iterate over shared attributes and output as JSON Object
value attributes = type(source).getAttributes<Source>(`SharedAnnotation`);
return Object {
for (attribute in attributes)
if (exists attributeValue = attribute(source).get())
attribute.declaration.name -> jsonValueOf(attributeValue)
};
}
}