as-json icon indicating copy to clipboard operation
as-json copied to clipboard

Add support for flattening complex properties

Open doxblek opened this issue 1 year ago • 1 comments

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.

doxblek avatar Apr 19 '23 05:04 doxblek

That's a great idea, @doxblek! I will look into it soon

JairusSW avatar May 04 '23 04:05 JairusSW

Hey, over a year late, but this is implemented now

JairusSW avatar Jun 18 '24 00:06 JairusSW