es6 将字符串转换为json,将符号的ES6类转换为JSON

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

var _postID = Symbol();

var _title = Symbol();

var _text = Symbol();

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; }

}

After the object is manipulated, I need to PUT and POST it back to the server. But it looks like Aurelia's HttpClient is sending an empty JSON string ({}). Looking into it, it seems that Symbols are ignored when converting an ES6 class to JSON.

How can I go about getting all my properties into a JSON string to submit back to the server?

解决方案

I'm assuming you're using symbols to keep the data private, but this means you're going to have to go through some extra steps if you want that data included in the JSON representation.

Here's an example using toJSON on your model to explicitly export the properties you care about

export class PostEdit {

// ...

toJSON() {

return {

postID: this.postID,

title: this.title,

text: this.text

};

}

}

Or

export class PostEdit {

// ...

toJSON() {

let {postID, title, text} = this;

return {postID, title, text};

}

}

When JSON.stringify is called on your instance, it will automatically call toJSON

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值