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

Javascript Typescript:如何用私有变量反序列化JSON对象?,javascript,json,typescript,local-storage,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 {

我有以下类型脚本模型对象
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!
我猜这与对象存储时使用的下划线有关。
如何正确接收对象?

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

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'));

JSON.parse
返回纯js对象(不是
User
类型)。您应该手动创建
User
实例并初始化它。可能会有帮助。