将符号的ES6类转换为JSON [英] Convert ES6 Class with Symbols to JSON

查看:385
本文介绍了将符号的ES6类转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个硬编码的类来代表我的Aurelia应用程序中的模型。这是一个模型'PostEdit':

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆