Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for flattening complex properties #46

Open
doxblek opened this issue Apr 19, 2023 · 1 comment
Open

Add support for flattening complex properties #46

doxblek opened this issue Apr 19, 2023 · 1 comment

Comments

@doxblek
Copy link

doxblek commented Apr 19, 2023

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.

@JairusSW
Copy link
Owner

JairusSW commented May 4, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants