JairusSW / as-json

The only JSON library you'll need for AssemblyScript. SIMD enabled
MIT License
80 stars 16 forks source link

Feature request: Support heterogeneous arrays #65

Closed dselman closed 5 months ago

dselman commented 7 months ago

It would be very useful for some use cases to support serialisation / deserialisation of heterogeneous arrays (via type inheritance). For example:

@json
abstract class Animal {
  name!: string;
  type!: string; 
  // add a decorator to mark this as the type discrimator
  // or allow a callback in options to pass a method to return the type at runtime?
}

@json
class Dog extends Animal {
    age!: i32;
}

@json
class Cat extends Animal {
    isVerified!: boolean;
}

@json
class Zoo {
  animals!: Animal[]
}

export function parse(stringified: string) : string {
  const zoo = JSON.parse<Zoo>(stringified, true);
  const out = JSON.stringify<Zoo>(zoo);
  return out;
}

And:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="module">
      import { parse } from "./build/release.js";
      const zoo = {
        animals: [
          {
            name: "Fido",
            type: "Dog",
            age: 10,
          },
          {
            name: "Tiddles",
            type: "Cat",
            isVerified: false,
          },
        ],
      };
      try {
        document.body.innerText = parse(JSON.stringify(zoo));
      } catch (err) {
        alert(err);
      }
    </script>
  </head>
  <body></body>
</html>
JairusSW commented 6 months ago

I can do this. Hm, I'll have time this weekend

JairusSW commented 5 months ago

Ooh, this is interesting:

@json
class Base {}

@json
class Vec1 extends Base {
  x: f32 = 0.0;
}
@json
class Vec2 extends Vec1 {
  y: f32 = 0.0;
}
@json
class Vec3 extends Vec2 {
  z: f32 = 0.0;
}

const arr: Base[] = [
  new Vec1(),
  new Vec2(),
  new Vec3()
];

console.log(JSON.stringify(arr));
JairusSW commented 5 months ago

And yes, this is implemented now. Sorry for getting back so late