as-json
as-json copied to clipboard
Add support for flattening complex properties
One feature that comparable libraries such as serde for Rust offer, is the ability to flatten inner objects. This would be a nice addition for as-json.
From usage perspective, this could look like this:
@json
class MyInnerClass {
first: string;
second: i32;
}
@json
class MyOuterClass {
otherProperty: f64;
@flatten
inner: MyInnerClass;
}
Serializing an instance of MyOuterClass
would result in JSON similar to this:
{
"otherProperty": 3.14,
"first: "Hello World",
"second": 42
}
The ability to flatten subproperties also helps to mitigate the shortcoming of AssemblyScript, that there are no nullable primitives as of today.
With flattening support this could be achieved like the following:
@json
class NullableI32 {
value: i32;
}
@json
class Foo {
@flatten
optionalInt: NullableI32 | null;
}
// ...
let nullJSON = `{"optionalInt": null}`; // Or `{}` with optionalInt being undefined
let valueJSON = `{"optionalInt": 42}`;
let nullFoo = JSON.parse<Foo>(nullJSON); // nullFoo.optionalInt == null
let valueFoo = JSON.parse<Foo>(valueJSON); // valueFoo.optionalInt != null && valueFoo.optionalInt.value == 42
Without flattening, it is impossible to not propagate the helper properties to the outside world.
That's a great idea, @doxblek! I will look into it soon
Hey, over a year late, but this is implemented now