Eljoy / ts-jackson

A typescript library to deserialize and serialize json into classes. You can use different path pattern to resolve deeply nested structures. Every path pattern provided by lodash/get|set object is supported. Check out src/examples as a reference.
https://www.npmjs.com/package/ts-jackson
MIT License
23 stars 2 forks source link

Polymorphism #8

Open manticorp opened 1 week ago

manticorp commented 1 week ago

Is there any way this library supports polymorphism?

e.g.

import { JsonProperty, Serializable, deserialize, serialize } from 'ts-jackson';

@Serializable()
class Polymorphic {}

@Serializable()
export class PolyA extends Polymorphic {
  @JsonProperty()
  name: string = 'PolyA';
  @JsonProperty()
  isSomethng: boolean = false;
}
@Serializable()
export class PolyB extends Polymorphic {
  @JsonProperty()
  name: string = 'PolyB';
  @JsonProperty()
  value: number = 50;
}

@Serializable()
export class HasPolymorphic {
  @JsonProperty({
    elementType: Polymorphic
  })
  public polys: Polymorphic[] = [];
}

const instance = new HasPolymorphic();

instance.polys.push(new PolyA());
instance.polys.push(new PolyB());

console.dir(instance);

const serialized = serialize(instance); // Uncaught TypeError: Cannot convert undefined or null to object
console.log(serialized);

const deserialized = deserialize(serialized, HasPolymorphic);
console.dir(deserialized);