简体   繁体   English

Typescript:如何用私有变量反序列化JSON object?

[英]Typescript: How to deserialize JSON object with private variables?

I have the following typescript model object user我有以下 typescript model object 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;
}

}

I store the object via this code:我通过以下代码存储 object:

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

If I look into the local storage there is the following string:如果我查看本地存储,则有以下字符串:

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

How do I get the user object again?如何再次获取用户 object?

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!

I guess this has something to to with the underscores the object is stored with.我想这与存储 object 的下划线有关。 How can I receive the object correctly?如何正确接收object?

You need to implement some serialize and deserialize methods in your model. 您需要在模型中实现一些序列化和反序列化方法。

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

Thanks to this answer to another post , I came up with this solution based on JSON.parse() 's reviver parameter:多亏了对另一篇文章的回答,我根据JSON.parse()reviver参数提出了这个解决方案:

const data = JSON.parse(json, function (key, value) {
    if (key.startsWith('_')) {
        this[key.slice(1)] = value
        return
    }
    return value
})

This works the other way around too with JSON.stringify() 's replacer parameter.这也适用于JSON.stringify()replacer参数。

Note that the callback won't work with an arrow function since they don't have their own binding to this请注意,回调不适用于箭头 function,因为它们没有自己this绑定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM