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

Classes derived from base classes do not deserialize correctly #90

Open
HeiLumi opened this issue Sep 11, 2024 · 1 comment
Open

Classes derived from base classes do not deserialize correctly #90

HeiLumi opened this issue Sep 11, 2024 · 1 comment

Comments

@HeiLumi
Copy link

HeiLumi commented Sep 11, 2024

json-as 0.9.21

in nasty example is problem in deserializing. Castings after deserialization does not work.

@json
class Base {}

@json
class Vec1 extends Base {
  x: f32 = 1.0;
}

@json
class Vec2 extends Vec1 {
  y: f32 = 2.0;
}

@json
class Vec3 extends Vec2 {
  z: f32 = 3.0;
}

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

const serialized = JSON.stringify(arr);
console.log("serialized: " + serialized);
// [{"x":1.0},{"x":1.0,"y":2.0},{"y":2.0,"x":1.0,"z":3.0}]
const parsed = JSON.parse<Base[]>(serialized);
console.log("parsed: " + parsed.length.toString());
//3

//castings not working
//all deserialized instances are type of 'Base', not derived class
for (let i = 0; i < parsed.length; i++) {
   if (parsed[i] instanceof Vec1) {
     console.log("Vec1, x=" +(<Vec1>parsed[i]).x.toString());
   }
   if (parsed[i] instanceof Vec2) {
    console.log("Vec2, y=" +(<Vec2>parsed[i]).y.toString());
  }
   if (parsed[i] instanceof Vec3) {
    console.log("Vec3, z=" +(<Vec3>parsed[i]).z.toString());
  }
}
@JairusSW
Copy link
Owner

@HeiLumi, this is a just how the type system works. If you did the same in TypeScript, you'd get the same results. The problem is that when they are given the parent class, they lose their upstream prototype signature, and so even though they have the right shape, there's no way to know.

Your turning each class to Base, so of course instanceof checks won't work here. Rather, you can add a type property to each class and check if (parsed[i].type === Vec1.type) for example

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