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

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

问题描述

我有硬编码的类来表示我的 Aurelia 应用程序中的模型.这是一个模型PostEdit":

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

}

在对象被操作后,我需要将它PUTPOST 返回到服务器.但看起来 AureliaHttpClient 正在发送一个空的 JSON 字符串 ({}).查看它,似乎在将 ES6 类转换为 JSON 时会忽略 Symbols.

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.

如何将我的所有属性放入 JSON 字符串以提交回服务器?

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

推荐答案

我假设您使用符号来保持数据的私密性,但这意味着如果您愿意,您将不得不执行一些额外的步骤JSON 表示中包含的数据.

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.

这是在模型上使用 toJSON 来显式导出您关心的属性的示例

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

export class PostEdit {

  // ...
  toJSON() {
    let {postID, title, text} = this;
    return {postID, title, text};
  }
}

当在您的实例上调用 JSON.stringify 时,它会自动调用 toJSON

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

这篇关于将带有符号的 ES6 类转换为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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