【问题标题】:Typescript: How to deserialize JSON object with private variables?Typescript:如何使用私有变量反序列化 JSON 对象?
【发布时间】:2016-11-18 18:28:08
【问题描述】:

我有以下打字稿模型对象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!

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

【问题讨论】:

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

标签: javascript json typescript local-storage


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多