JSON到Javascript类

TSR*_*TSR 4 javascript oop class object object-oriented-database

我有一个http请求,它从nosql数据库获取此Json对象:

let jsonBody = {
    birthday : 1997,
    firstname: 'foo',
    lastname:'bar'
}
Run Code Online (Sandbox Code Playgroud)

然后,我想将此信息加载到Student模型中:

class Student{
    constructor(){

    }

    getFullname(){
        return this.lastname+' '+this.firstname
    }
    getApproxAge(){
        return 2018- this.birthday
    }
}
Run Code Online (Sandbox Code Playgroud)

通常,我会将此方法添加到此类中:

fromJson(json){
    this.studentId = json.studentId;
    this.birthday = json.birthday;
    this.firstname = json.firstname;
    this.lastname = json.lastname;
}
Run Code Online (Sandbox Code Playgroud)

我将使用它如下:

let student = new Student()
student.fromJson(jsonBody)
console.log(student.getFullname())
console.log(student.getApproxAge())
Run Code Online (Sandbox Code Playgroud)

这很好,但我的问题是我有:现实中有100个专有权。我是否必须使用fromJson方法一一列出所有属性?

而且,如果专有名称发生了更改,那么说:姓氏变为姓氏,我将不得不对其进行修复?

有没有更简单的方法将这些值动态地分配给对象学生,但保留其所有方法呢?

像这样:

fromJson(json){
    this = Object.assign(this, json) //THIS IS NOT WORKING
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*lms 11

只需分配一个实例:

 static from(json){
   return Object.assign(new Student(), json);
 }
Run Code Online (Sandbox Code Playgroud)

因此,您可以执行以下操作:

 const student = Student.from({ name: "whatever" });
Run Code Online (Sandbox Code Playgroud)

或将其设为实例方法并忽略赋值:

 applyData(json) {
   Object.assign(this, json);
 }
Run Code Online (Sandbox Code Playgroud)

这样你就可以:

 const student = new Student;
 student.applyData({ name: "whatever" });
Run Code Online (Sandbox Code Playgroud)

它也可以是构造函数的一部分:

 constructor(options = {}) {
  Object.assign(this, options);
 }
Run Code Online (Sandbox Code Playgroud)

然后,您可以执行以下操作:

 const student = new Student({ name: "whatever" });
Run Code Online (Sandbox Code Playgroud)

而且,如果属性名称已更改,则说:lastname成为LastName,我将不得不对其进行修复?

是的,您将不得不解决该问题。


小智 7

javascript 中无法将 json 反序列化为类。所以我写了一个库ts-serialized来解决这个问题。

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

export class User extends Serializable {

    @jsonProperty(String)
    public firstName: string = ''; // default value necessarily

    @jsonProperty(String, void 0)
    public lastName?: string = void 0; // default value necessarily

    @jsonProperty(Date)
    public birthdate: Date = new Date(); // default value necessarily

    public getFullName(): string {
        return [
            this.firstName,
            this.lastName
        ].join(' ');
    }

    public getAge(): number {
        return new Date().getFullYear() - this.birthdate.getFullYear();
    }
}

const user: User = new User().fromJSON(json);
user.getFullName(); // work fine and return string
user.getAge(); // work fine and return number

// or
const user: User = User.fromJSON(json);
user.getFullName(); // work fine and return string
user.getAge(); // work fine and return number
Run Code Online (Sandbox Code Playgroud)

该库还在反序列化期间检查类型。