Convert ES6 Class with Symbols to JSON

后端 未结 5 1866
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 23:31

I have hardcoded classes to represent models in my Aurelia application. Here\'s a model \'PostEdit\':

var _postID = Symbol();
var _title = Symbol();
var _te         


        
5条回答
  •  一生所求
    2020-12-09 00:01

    Give your class a toJSON method that returns a stringifyable object:

    export class PostEdit {
    
        constructor(postEdit) {
            this[_postID] = postEdit.postID;
            this.title = postEdit.title;
            this.text = postEdit.text;
        }
    
        get postID() { return this[_postID]; }
    
        get title() { return this[_title]; }
        set title(val) { this[_title] = val; }
    
        get text() { return this[_text]; }
        set text(val) { this[_text] = val; }
    
        toJSON() {
            return {
                postId: this.postId,
                title: this.title,
                text: this.text
            };
        }
    }
    

    JSON.stringify will automatically call that and replace your instance with the result.

    Also you might want to add a fromJSON method to your class that you can use to revive instances during JSON.parse. It is trivial in your case:

        static fromJSON(obj) {
            return new this(obj);
        }
    

    but you might need something more complicated in other classes.

提交回复
热议问题