将符号的ES6类转换为JSON [英] Convert ES6 Class with Symbols to JSON
问题描述
var _postID = Symbol();
var _title = Symbol();
var _text = Symbol();
export class PostEdit {
构造函数(postEdit){
这个[_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; }
}
对象被操纵后,我需要 PUT
和 POST
它回到服务器。但是它看起来像 Aurelia
的 HttpClient
正在发送一个空的 JSON
string( {}
)。看看它,在将ES6类转换为 JSON
时,似乎忽略符号
。
如何将所有属性都转到 JSON
字符串中以提交回服务器? p>
我假设您正在使用符号来保持数据的私密性,但这意味着您将不得不经历一些额外的步骤,如果你想要这个数据包含在JSON表示。
这里是一个例子,使用你的模型中的 toJSON
明确导出您关心的属性
export class PostEdit {
// ...
toJSON(){
return {
postID:this.postID,
title:this.title,
text:this.text
};
}
}
或
export class PostEdit {
// ...
toJSON(){
let {postID,title,text } =这个
return {postID,title,text};
}
}
当 JSON.stringify
在您的实例上调用,它会自动调用 toJSON
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
这篇关于将符号的ES6类转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!