Typescript:如何使用私有变量反序列化JSON对象?

时间:2016-07-15 13:54:14

标签: javascript json typescript local-storage

我有以下打字稿模型对象user

export class User {

constructor(
    private _name: string,
    private _email: string
)  {}


public get name():string {
    return this._name;
}

public set name(value:string) {
    this._name = value;
}

get email():string {
    return this._email;
}

set email(value:string) {
    this._email = value;
}

}

我通过以下代码存储对象:

let user = new User('myName', 'myEmail');
localStorage.setItem('user', JSON.stringify(user));

如果我查看本地存储,则会出现以下字符串:

{"_name":"myName","_email":"myEmail"}

如何再次获取用户对象?

let user: User = JSON.parse(localStorage.getItem('user'));
console.log(user.name); // logs undefined. Should log 'myName'
console.log(user._name); // this logs 'myName'. But according to the typescript documentation this should NOT work!

我想这与存储对象的下划线有关。 如何正确接收物体?

1 个答案:

答案 0 :(得分:0)

您需要在模型中实现一些序列化和反序列化方法。

class User {
    static public deserialize(serialized) {
        const {name, email} = JSON.parse(serialized);
        return new User(name, email);
    }    

    constructor(
        private _name: string,
        private _email: string
    )  {}


    public get name():string {
        return this._name;
    }

    public set name(value:string) {
        this._name = value;
    }

    get email():string {
        return this._email;
    }

    set email(value:string) {
        this._email = value;
    }

    public serialize() {
        return JSON.stringify({name: this.name, email: this.email});
    }

}

let user = new User('myName', 'myEmail');
localStorage.setItem('user', user.serialize());

let user1: User = User.deserialize(localStorage.getItem('user'));