我有以下 typescript 模型对象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'));
关于javascript - Typescript:如何使用私有(private)变量反序列化 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38397898/