mobxjs / serializr

Serialize and deserialize complex object graphs to and from JSON and Javascript classes
MIT License
766 stars 52 forks source link

How to divide a json data into multiple classes by serializr? #71

Closed tangxinyao closed 6 years ago

tangxinyao commented 6 years ago

Now I have a serialized json data like this:

{
  "id" : "id", 
  "name" : "somebody",
  "mobile" : "number",
  "email" : "somebody@mail.com"
}

I wonder if I could convert the json data to a plain object like this:

class Base {
  id: string;
  name: string;
}
class Contact {
  mobile: string;
  email: string; 
}
class User {
  base: Base;
  contact: Contact
}

which means, a json should be broken up into two object here.

alexggordon commented 6 years ago

Yeah, so there's nothing that really supports that out of the box. You might be able to do something with references, but that would still require some sort of duplicate deserialization.

You might be able to do something magical with getters or setters, or dependency injection, depending on your needs. Something like,

class Base {
  user;
  constructor(user) {
    this.user = user
  }

  get id() {
    return this.user.id;
  }

  get name() {
    return this.user.name;
  }
}

class Contact {
  user;
  constructor(user) {
    this.user = user
  }

  get mobile() {
    return this.user.mobile;
  }

  get email() {
    return this.user.email;
  }
}

class User {
  @serializable(identifier()) id;
  @serializable name;
  @serializable mobile;
  @serializable email;
  base;
  contact;

  constructor() {
    this.base = Base.new(this);
    this.contact = Contact.new(this);
  }
}

Does that do basically what you need it to?