Serializable icon indicating copy to clipboard operation
Serializable copied to clipboard

Extract fromJson/toJson methods into standalone functions

Open cameronhimself opened this issue 4 months ago • 3 comments

Hi, thanks so much for writing this! It looks like it's perfect for my purposes.

I was wondering if it would be possible to have fromJson and toJson functions, rather than methods on the Serializable class. This would provide more flexibility, since classes could retain their existing inheritance chains.

So, instead of this:

import { jsonProperty, Serializable } from "ts-serializable";

class User extends Serializable {
  @jsonProperty(String)
  public firstName: string = '';

  @jsonProperty(String, void 0)
  public lastName?: string = void 0;
}

const userData = { firstName: "John", lastName: "Doe" };
const user = new User().fromJson(userData);
const userSerialized = user.toJson();

Maybe this:

import { jsonProperty, toJson, fromJson } from "ts-serializable";

class User {
  @jsonProperty(String)
  public firstName: string = '';

  @jsonProperty(String, void 0)
  public lastName?: string = void 0;
}

const userData = { firstName: "John", lastName: "Doe" };
const user = fromJson(userData, User);
const userSerialized = toJson(user); // or toJson(user, User), if necessary

cameronhimself avatar Sep 21 '25 00:09 cameronhimself

Brilliant idea! People periodically ask me for an implementation without inheriting from Serializable. The only idea I had was monkey patching, but that's an anti-pattern. Your idea allows implementing serialization and deserialization without inheriting from Serializable and without resorting to anti-patterns. I'll implement this functionality in a few days.

LabEG avatar Sep 22 '25 07:09 LabEG

Any update on this by chance?

cameronhimself avatar Oct 17 '25 15:10 cameronhimself

Sorry for the delayed response. There were some minor issues. Please try the latest version.

I didn't have time to test it on a real project, but I hope the library's autotests provide sufficient coverage. If any problems arise, please let me know.

LabEG avatar Oct 18 '25 13:10 LabEG